0

考虑以下两个数据框:

> df1 <- data.frame(vals = c("a","b","c"), index = 1:3)
> 
> df1
  vals index
1    a     1
2    b     2
3    c     3
> 
> df2 <- data.frame(a = c("x1","x2","x3"), b = c("a,b,c","b,c","a,c"))
> 
> df2
   a     b
1 x1 a,b,c
2 x2   b,c
3 x3   a,c

我试图用列作为匹配条件的数据b框中的值替换数据框中df2的值。但是,数据框的列是逗号分隔的字符串,这使得它更加复杂。indexdf1valsbdf2

任何人都可以帮忙吗?

4

1 回答 1

0
df2$c <- sapply(strsplit(as.character(df2$b),","),function(x) {
                 paste(df1[na.omit(match(x,df1$vals)),"index"],collapse=",")
                })

#    a     b     c
# 1 x1 a,b,c 1,2,3
# 2 x2   b,c   2,3
# 3 x3   a,c   1,3
于 2013-06-04T07:25:33.703 回答