我有一个框架数据“testData”,如下所示:
id content
1 I came from China
2 I came from America
3 I came from Canada
4 I came from Japan
5 I came from Mars
而且我还有另一个帧数据“addr”,如下所示:
id addr
1 America
2 Canada
3 China
4 Japan
然后,如何在R中使用
grepl
,sapply
或任何其他有用的函数来生成数据,如下所示:id content addr
1 I came from China China
2 I came from America America
3 I came from Canada Canada
4 I came from Japan Japan
5 I came from Mars Mars
最佳答案
这可以解决问题:
vec = addr$addr
testData$addr = apply(testData, 1, function(u){
bool = sapply(vec, function(x) grepl(x, u[['content']]))
if(any(bool)) vec[bool] else NA
})