我看起来或多或少的数据是这样的:
data1 <- data.frame(col=c("Peter i.n.","Victor Today Morgan","Obelix","One More"))
data2 <- data.frame(num=c(123,434,545,11,22),col=c("Victor Today","Obelix Mobelix is.",
"Peter Asterix i.n.","Also","Here"))
我希望在两个数据框架中匹配名称,并将列num
放入data1。
期望的结果:
col num
1 Peter i.n. 545
2 Victor Today Morgan 123
3 Obelix 434
我试过这个,但没有按预期工作。
filter <- sapply(as.character(data1$col), function(x) any(grepl(x,as.character(data2$col))))
data1$num <- data2[filter,]
答案 0 :(得分:2)
firstName <- function(x) sub(" .*", "", x)
data1$num <- data2$num[match(firstName(data1$col), firstName(data2$col))]
data1[!is.na(data1$num),]
答案 1 :(得分:2)
如果您不清楚自己想要查看哪些col
名称(data1
或data2
),则可以通过以下方式使用自己的解决方案:
data2[as.logical(sapply(gsub(" .*", "", as.character(data2$col)), function(x) any(grepl(x, as.character(data1$col))))), ]
## num col
## 1 123 Victor Today
## 2 434 Obelix Mobelix is.
## 3 545 Peter Asterix i.n.
这会将data2$col
中的第一个字与data1$col
匹配,并从data2