R中DataFrame中的求和列

Sum column in a DataFrame in R

我正在尝试将一个总和列添加到一个包含日期的大文件中。我想每个月求和,在当月最后一列右边加一列

下面是一个可重现的例子:

df <- data.frame("6Jun06" = c(4, 5, 9),
    "13Jun06" = c(4, 5, 9),
    "20Jun06" = c(4, 5, 9),
    "03Jul16" = c(1, 2, 3),
    "09Jul16" = c(1, 2, 3),
    "01Aug16" = c(1, 2, 5))

所以在这种情况下,我需要有三列(在 Jun、Jul 和 Aug 之后)。

  X6.Jun.06 X13.Jun.06 X20.Jun.06 Jun.Sum X03.Jul.16 X09.Jul.16 Jul.Sum X01.Aug.16 Aug.Sum
1         4          4          4     Sum          1          1     Sum          1     Sum
2         5          5          5     Sum          2          2     Sum          2     Sum
3         9          9          9     Sum          3          3     Sum          5     Sum

我不确定如何单独计算每个月的总和。我知道有内置求和函数,但我尝试的函数不适合我的问题,因为它们只是做一般求和。

您使用以数字开头的变量名称会让您自己的生活变得有些困难,因为 R 会在它们前面插入一个 X。但是,您可以通过以下一种方式获得所需的金额。

#1. Use the package `reshape2`:

    library(reshape2)
    dfm <- melt(df)

#2.  Get rid of the X in the dates, then convert to a date using the package `lubridate` and extract the month:

    library(lubridate) 
    dfm$Date <- dmy(substring(dfm$variable, 2))
    dfm$Month <- month(dfm$Date)

#3. Then calculate the sum for each month using the `dplyr` package:

    library(dplyr)
    dfm %>% group_by(Month) %>% summarise(sum(value))

这是一种在数据框末尾添加新列的方法,

cbind(df, sapply(unique(gsub('\d+', '', names(df))), function(i)
                          rowSums(df[grepl(i, sub('\d+', '', names(df)))])))

#  6Jun06 13Jun06 20Jun06 03Jul16 09Jul16 01Aug16 Jun Jul Aug
#1      4       4       4       1       1       1  12   2   1
#2      5       5       5       2       2       2  15   4   2
#3      9       9       9       3       3       5  27   6   5

如果您是 R 的新手,那么了解 dplyr 生态系统(以及 Hadley Wickham 的其他软件包)是一个好的开始。

library(dplyr)
library(tidyr)

df %>%
   mutate(id = 1:nrow(df)) %>%
   gather(date, value, -id) %>%
   mutate(Month = month.abb[apply(sapply(month.abb, function(mon) {grepl(mon, .$date)}), 1, which)]) %>%
   group_by(id, Month) %>%
   summarize(sum = sum(value)) %>%
   spread(Month, sum) %>%
   left_join(mutate(df, id = 1:nrow(df)), .) %>%
   select(-id)