R:对具有相同变量(列名)的两个/多个数据框的逐列值求和,并以日期列为参考



我想对具有相似列的两个数据框求和,并以日期列为参考。例如:

DF1:

Date  V1  V2  V3  
2017/01/01   2   4   5   
2017/02/01   3   5   7 

DF2:

Date  V1  V2  V3  
2017/01/01   1   3   6  
2017/02/01   5   7   7

我希望结果为:

DF3:

Date  V1  V2  V3  
2017/01/01   3   7  11  
2017/02/01   8  12  14

当我尝试添加 df1 和 df2 时,它给出了错误,因为无法连接日期。合并在这里也没有用,因为这是对相似数据框的值求和。

可以考虑以下基本 R 方法。

df3 <- cbind(df1[1], df1[-1] + df2[-1])
df3
Date V1 V2 V3
1 2017/01/01  3  7 11
2 2017/02/01  8 12 14

或者dplyr方法。

library(dplyr)
df3 <- bind_rows(df1, df2) %>%
group_by(Date) %>%
summarise_all(funs(sum))
df3
Date    V1    V2    V3
<chr> <int> <int> <int>
1 2017/01/01     3     7    11
2 2017/02/01     8    12    14

或者data.table方法。

library(data.table)
df_bind <- rbindlist(list(df1, df2))
df3 <- df_bind[, lapply(.SD, sum), by = Date]
df3
Date V1 V2 V3
1: 2017/01/01  3  7 11
2: 2017/02/01  8 12 14

数据:

df1 <- read.table(text = "Date    V1    V2    V3  
'2017/01/01' 2    4    5   
'2017/02/01' 3    5    7",
header = TRUE, stringsAsFactors = FALSE)
df2 <- read.table(text = "Date    V1    V2    V3  
'2017/01/01'    1    3     6  
'2017/02/01'    5    7     7",
header = TRUE, stringsAsFactors = FALSE)

这应该有效:

df = rbind(df1,df2)
aggregate(df[,2:4],by=list(date = df$Date),sum)

你可以做这样的事情:

pp <- cbind(names=c(rownames(df1), rownames(df2)), 
rbind.fill(list(df1, df2)))

然后,您可以使用plyr'sddply进行聚合,如下所示:

ddply(pp, .(names), function(x) colSums(x[,-1], na.rm = TRUE))

最新更新