在R中查找列表元素 [英] Finding Elements of Lists in R
问题描述
现在,我正在使用R中的字符向量,我使用strsplit逐词分隔.我想知道是否有一个函数可以用来检查整个列表,查看列表中是否有特定单词,并(如果可能)说出列表中的哪个元素.
Right now I'm working with a character vector in R, that i use strsplit to separate word by word. I'm wondering if there's a function that I can use to check the whole list, and see if a specific word is in the list, and (if possible) say which elements of the list it is in.
例如.
a = c("a","b","c")
b= c("b","d","e")
c = c("a","e","f")
如果为z=list(a,b,c)
,则f("a",z)
最佳生成[1] 1 3
,而f("b",z)
最佳生成[1] 1 2
If z=list(a,b,c)
, then f("a",z)
would optimally yield [1] 1 3
, and f("b",z)
would optimally yield [1] 1 2
任何帮助都会很棒.
推荐答案
正如alexwhan所说,grep
是要使用的函数.但是,请小心将其与列表一起使用.它没有做您可能认为正在做的事情.例如:
As alexwhan says, grep
is the function to use. However, be careful about using it with a list. It isn't doing what you might think it's doing. For example:
grep("c", z)
[1] 1 2 3 # ?
grep(",", z)
[1] 1 2 3 # ???
幕后发生的事情是grep
使用as.character
将其第二个参数强制转换为character.当应用于列表时,as.character
返回的是该列表通过解析得到的字符表示形式. (取消公开列表的模版.)
What's happening behind the scenes is that grep
coerces its 2nd argument to character, using as.character
. When applied to a list, what as.character
returns is the character representation of that list as obtained by deparsing it. (Modulo an unlist.)
as.character(z)
[1] "c(\"a\", \"b\", \"c\")" "c(\"b\", \"d\", \"e\")" "c(\"a\", \"e\", \"f\")"
cat(as.character(z))
c("a", "b", "c") c("b", "d", "e") c("a", "e", "f")
这是grep
正在处理的.
如果要在列表上运行grep
,更安全的方法是使用lapply
.这将返回另一个列表,您可以对其进行操作以提取您感兴趣的内容.
If you want to run grep
on a list, a safer method is to use lapply
. This returns another list, which you can operate on to extract what you're interested in.
res <- lapply(z, function(ch) grep("a", ch))
res
[[1]]
[1] 1
[[2]]
integer(0)
[[3]]
[1] 1
# which vectors contain a search term
sapply(res, function(x) length(x) > 0)
[1] TRUE FALSE TRUE
这篇关于在R中查找列表元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!