2013-01-03 124 views
2

我有兩個數據框,它們具有相同的3列:WeekNum,Year和Number。根據2個匹配列值將數據從一個數據框添加到另一個數據框

A <- data.frame(WeekNum=c(1,2,3,4,5,1,2,3,4,5), 
       Year=c(2000,2000,2000,2000,2000,2001,2001,2001,2001,2001), 
       Number=c(0,0,0,0,0,0,0,0,0,0)) 

B <- data.frame(WeekNum=c(1,2,3,4,1,2,6), 
       Year=c(2000,2000,2000,2000,2001,2001,2001), 
       Number=c(0,1,0,1,2,5,6)) 

我想創建一個新的數據幀使用所有WEEKNUM和年份組合從A(並且只有那些從B中也存在於A)相同的3列。當在B中同時存在WeekNum和Year組合時,我想使用來自B的數值。如果組合不存在於B中,我希望將Number值保留爲0.最終,我應該有一個數據框看起來像:

> C 
    WeekNum Year Number 
1  1 2000  0 
2  2 2000  1 
3  3 2000  0 
4  4 2000  1 
5  5 2000  0 
6  1 2001  2 
7  2 2001  5 
8  3 2001  0 
9  4 2001  0 
10  5 2001  0 

回答

4

一個簡單的方法是將兩個data.frames AB創建id列,然後使用match

A$id <- paste(A$WeekNum, A$Year, sep=":") 
B$id <- paste(B$WeekNum, B$Year, sep=":") 

m1 <- match(A$id, B$id) 
m2 <- which(!is.na(m1)) 
A$Number[m2] <- B$Number[m1[!is.na(m1)]] 
subset(A, select=-c(id)) 

輸出:(Edit:我看你改變了你的輸入data.frame

WeekNum Year Number 
1  1 2000  0 
2  2 2000  1 
3  3 2000  0 
4  4 2000  1 
5  5 2000  0 
6  1 2001  2 
7  2 2001  5 
8  3 2001  0 
9  4 2001  0 
10  5 2001  0 
0

從@Arun答案之前的變化:如需要

數據綁定在一起:

result <- rbind(
A[!(paste(A$WeekNum, A$Year, sep=":") %in% paste(B$WeekNum, B$Year, sep=":")),], 
B[paste(B$WeekNum, B$Year, sep=":") %in% paste(A$WeekNum, A$Year, sep=":"),] 
) 

排序,以得到正確的順序:

result <- result[order(result$Year,result$WeekNum),] 

    WeekNum Year Number 
51  1 2000  0 
6   2 2000  1 
7   3 2000  0 
81  4 2000  1 
5   5 2000  0 
91  1 2001  2 
101  2 2001  5 
8   3 2001  0 
9   4 2001  0 
10  5 2001  0 
相關問題