2011-08-25 17 views
2
a=c("A","A,B","C","B,C") 
b=c(1,2,3,4) 
dat<-data.frame(a,b) 

c=c("A","B","D","A") 
d=c(5,6,7,8) 
g<-data.frame(c,d) 

我想比較dat和g。如果dat列a中的元素與g中列c的元素相匹配,則g中列d的匹配項應添加到dat中。將strsplit逐行應用並將列添加到數據

dat$NEW ="" 
sapply(strsplit(as.character(dat$a), ","),function(x){tmp=grep(x,g$c);dat$NEW=x) 

我怎樣才能讓:在DAT $ NEW

g[grep("A",g$c),] 
    c d 
1 A 5 
4 A 8 

條目應該看起來像 「5,8」?

回答

1

這是適用於您的數據?

find.match <- g$c %in% dat$a 
g[find.match, ] 
    c d 
1 A 5 
4 A 8 
+0

感謝您的回覆,但是我在dat中丟失了命中「B」的數字「A,B」 – Jasmine

0

這並不完全清楚,但是這有什麼,我認爲你的描述:

步驟1:將您的data.frame摹複製的元素

> gc <- sapply(split(g$d, g$c), paste, collapse=",") 
> gc 
    A  B  D 
"5,8" "6" "7" 

步驟2:將本到您的data.frame DAT

cbind(dat, 
    new=sapply(
     dat$a, 
     function(x)paste(
       gc[match(strsplit(as.character(x), ",")[[1]], g$c)], 
       collapse=",") 
    ) 
) 

結果:

a b new 
1 A 1 5,8 
2 A,B 2 5,8,6 
3 C 3 NA 
4 B,C 4 6,NA 
+0

太棒了!我想擴展我的g: c = c(「A,B」,「B」,「D」,「A」) d = c(5,6,7,8) g <-data .frame(c,d) dat中的「A」應該與g(「A,B」,「A」)中出現的「A」匹配,那麼我必須使用grep? – Jasmine

+0

可能有涉及'grep'的解決方案,但我修改了我的答案,通過使用'strsplit'和'match'來給出我想要的結果 – Andrie