R:将列与数据框中的其他列匹配并保存它们

时间:2017-03-06 12:12:07

标签: r match

我有2个数据帧df1和df2。

df1 <- data.frame(ID = c("aa", "ab", "ac", "ad", "ae", "af"), y = 1:6 )
df2 <- data.frame(x = c("aa","ac", "aa", "ac", "ab","aa","fa"), obj=c("F70", "F60", "F71", "F82", "F92", "F62"))

我想将“ID”和“x”列df1与df2匹配,然后将df2中的obj列保存在使用该匹配转置的df1中。这样我得到了:

ID y 
aa 1 F70 F71 F62
ab 2 F92 NA  NA
ac 3 F60 F82 NA
ad 4 NA  NA  NA
ae 5 NA  NA  NA
af 6 NA  NA  NA

1 个答案:

答案 0 :(得分:1)

您可以使用df2重新格式化data.table,然后与df1合并:

library(data.table)
df1 <- data.frame(ID = c("aa", "ab", "ac", "ad", "ae", "af"), y = 1:6 )
df2 <- data.frame(x = c("aa","ac", "aa", "ac", "ab","aa"), obj=c("F70", "F60", "F71", "F82", "F92", "F62"))

# split and collapse df2
df2.collapse <- sapply(split(df2$obj, f = df2$x), function(x) paste(x, collapse = ','))

# make a new df2
df2.new <- data.frame(ID = names(df2.collapse), tstrsplit(df2.collapse, ','))

# merge with df1, you may want to change the colnames of new columns
merge(df1, df2.new, by = 'ID', all.x = T)
#   ID y c..F70....F92....F60.. c..F71...NA...F82.. c..F62...NA..NA.
# 1 aa 1                    F70                 F71              F62
# 2 ab 2                    F92                <NA>             <NA>
# 3 ac 3                    F60                 F82             <NA>
# 4 ad 4                   <NA>                <NA>             <NA>
# 5 ae 5                   <NA>                <NA>             <NA>
# 6 af 6                   <NA>                <NA>             <NA>