2011-09-28 43 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將只返回第一個匹配。