我是R的新手,一直在为此而苦苦挣扎。我想创建一个新列,检查列'text'中是否存在任何单词(“foo”,“x”,“y”),然后将该值写入新列。R:提取和粘贴关键字匹配
我有看起来像这样的数据帧:A->
id text time username
1 "hello x" 10 "me"
2 "foo and y" 5 "you"
3 "nothing" 15 "everyone"
4 "x,y,foo" 0 "know"
正确的输出应为:
A2 - >
id text time username keywordtag
1 "hello x" 10 "me" x
2 "foo and y" 5 "you" foo,y
3 "nothing" 15 "everyone" 0
4 "x,y,foo" 0 "know" x,y,foo
我有这样的:
df1 <- data.frame(text = c("hello x", "foo and y", "nothing", "x,y,foo"))
terms <- c('foo', 'x', 'y')
df1$keywordtag <- apply(sapply(terms, grepl, df1$text), 1, function(x) paste(terms[x], collapse=','))
哪个有效,但当我的needleList包含12k个单词并且我的文本有155k个行时崩溃R.有没有办法做到这一点,不会崩溃R?
看起来效率很低。你为什么不研究已经解决这个问题的软件包。 –
也许在stringr库中试试这样的东西:sapply(df1,function(x)str_extract_all(x,paste(terms,collapse =“|”))) – Wyldsoul
'needleList'是什么? – steveb