Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从R中的文本列表中提取单词?_R_Stringr - Fatal编程技术网

如何从R中的文本列表中提取单词?

如何从R中的文本列表中提取单词?,r,stringr,R,Stringr,我想从我的观察中提取一些具体的词语,如果这些词语存在的话 a = c("friend", "cat", "dog") b = "my friend has a dog" 如果我使用类似 results <- str_extract_all(b,a) 结果我们可以使用stru c将它们粘贴到单个字符串中,现在它应该可以工作了 library(stringr) str_extract_all(b, str_c(

我想从我的观察中提取一些具体的词语,如果这些词语存在的话

a = c("friend", "cat", "dog")
b = "my friend has a dog"
如果我使用类似

results <- str_extract_all(b,a)

结果我们可以
使用
stru c
将它们粘贴到单个字符串中,现在它应该可以工作了

library(stringr)
str_extract_all(b, str_c(a, collapse="|"))[[1]]
#[1] "friend" "dog"  

或者通过
unlist

unlist(str_extract_all(b, a))
#[1] "friend" "dog"  

使用
regmatches

> unlist(regmatches(b, gregexpr(paste0(a, collapse = "|"), b)))
[1] "friend" "dog"


它起作用了!非常感谢你!因为我需要将它扩展到更复杂的问题,所以在第一个解决方案中,[[1]]的作用是什么?@emmecicubo,它返回一个元素的
列表。因此,要么使用
取消列表
,要么只提取第一个列表元素
[
> intersect(unlist(strsplit(b, "\\W+")), a)
[1] "friend" "dog"