2011-09-28 39 views
4

我有一个数据帧,看起来像基于共同的价值总结2个dataframes

day.of.week count 
1   0  3 
2   3  1 
3   4  1 
4   5  1 
5   6  3 

和其他类似

day.of.week count 
1   0 17 
2   1  6 
3   2  1 
4   3  1 
5   4  5 
6   5  1 
7   6 13 

我想从DF1添加值DF2基于对day.of.周。我试图使用ddply

total=ddply(merge(total, subtotal, all.x=TRUE,all.y=TRUE), 
        .(day.of.week), summarize, count=sum(count)) 

它几乎工作,但合并结合具有共享值的行。例如上面day.of.week = 5的例子。而不是合并到每个计数为1的两条记录,而是合并到计数为1的一条记录中,所以不是总数为2,而是总数为1。

 day.of.week count 
    1   0  3 
    2   0 17 
    3   1  6 
    4   2  1 
    5   3  1 
    6   4  1 
    7   4  5 
    8   5  1 
    9   6  3 
    10   6 13 
+0

尝试通过'= “day.of.week”',而不是'all.x = TRUE', 'all.y = TRUE' ... –

回答

7

没有必要合并。你可以简单地做

ddply(rbind(d1, d2), .(day.of.week), summarize, sum_count = sum(count)) 

我假定这两个数据帧具有相同的列名day.of.weekcount

+0

我太努力了。谢谢。 –

1

除了奔就给大家介绍使用merge的建议,你也可以做到这一点简单地使用子集:

d1 <- read.table(textConnection(" day.of.week count 
1   0  3 
2   3  1 
3   4  1 
4   5  1 
5   6  3"),sep="",header = TRUE) 

d2 <- read.table(textConnection(" day.of.week count1 
1   0 17 
2   1  6 
3   2  1 
4   3  1 
5   4  5 
6   5  1 
7   6 13"),sep = "",header = TRUE) 

d2[match(d1[,1],d2[,1]),2] <- d2[match(d1[,1],d2[,1]),2] + d1[,2] 
> d2 
    day.of.week count1 
1   0  20 
2   1  6 
3   2  1 
4   3  2 
5   4  6 
6   5  2 
7   6  16 

这是假定没有重复day.of.week行,因为match将只返回第一个匹配。