-2

Hi How do i apply lappy() to the values in rows?

Lets say my dataset is

Name     value      month
SP        50       January
Mary      67       January
Justin    33       January

SP        45       February
Mary      37       February
Justin    53       February

SP        55       March
Mary      67       March
Justin    23       March

So if i need to find the sum of values for each month, to get my out put as:

Month        Value
January       150
February      135
March         145

Currently i only know how to calculate this on the whole without the monthly separation as in:

library(tidyverse)
x <- tibble(Name = c("SP","Mary","Justin","SP","Mary","Justin","SP","Mary","Justin"),
            value = c(50,67,33,45,37,53,55,67,23),
            Month = c("January", "January", "February", "February","March","March"))
y <- data.frame(x,sum(x$value))

I do not know how to get my desired outcome. any idea how?

AlisonGrey
  • 497
  • 1
  • 7
  • 23

1 Answers1

-2

We can use aggregate from base R

aggregate(value ~ Month, x, sum)

Or with dplyr

library(dplyr)
x %>%
   group_by(Month) %>%
   summarise(value = sum(value))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • if my calculation gets complicated, say, multiple levels of calculations, will i still be able to use the same format? – AlisonGrey May 10 '19 at 06:16
  • @SPishere With `dplyr`, it is more easier as you can chain `%>%` the calculations with `mutate/summarise` and other functions `select/arrange` etc. You can check the vignettes of tidyverse as it could be useful for you – akrun May 10 '19 at 06:18