【发布时间】:2018-02-06 00:17:31
【问题描述】:
总的新手 R 问题。我有一个 ID 和注释的数据框 df:
ID Notes
1 dogs are friendly
2 dogs and cats are pets
3 cows live on farms
4 cats and cows start with c
我还有另一个值“动物”列表
cats
cows
我想在我的数据框中添加另一列“匹配”,其中包含注释中的所有动物,例如
ID Notes Matches
1 dogs are friendly
2 dogs and cats are pets cats
3 cows live on farms cows
4 cats and cows start with c cats, cows
到目前为止,我唯一的运气是使用 grepl 如果有任何匹配项返回:
grepl(paste(animals,collapse="|"),df$Notes,ignore.case = T)
如何改为返回值?
更新
在我的数据框中有一些行,我有多个猫的实例,例如,在我的笔记中:
ID Notes Matches
1 dogs are friendly
2 dogs and cats are pets cats
3 cows live on farms cows
4 cats and cats cows start with c cats, cows
我只想返回一个匹配实例。 @LachlanO 让我非常接近他的解决方案,但我明白了:
[1] "NA, NA" "cats, NA" "NA, cows" "c(\"cats\", \"cats\"), cows"
如何只返回不同的匹配项?
【问题讨论】:
-
试试
stringr::str_extract_allinsted ofgrepl。 -
或类似:
df$Matches <- sapply(strsplit(tolower(df$Notes), " "), function(x) toString(intersect(x, animals)))