开发者

apply strsplit rowwise and add column to data

开发者 https://www.devze.com 2023-03-30 09:13 出处:网络
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)
 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)

I would like to co开发者_StackOverflow社区mpare dat and g. If elements in column a of dat matches an element of column c in g, matched entry of column d in g should be added to dat.

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

How can I make :

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

entry in dat$NEW should look like "5,8" ?


Is this working for your data?

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


It's not entirely clear, but this what I think you describe:

Step 1: Combine duplicated elements in your data.frame g

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

Step 2: Combine this into your data.frame dat

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

Results:

    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

精彩评论

暂无评论...
验证码 换一张
取 消