繁体   English   中英

如何直接引用向量而不是嵌套 lapply function 中的列表?

[英]How can I reference the vectors directly and not the list in a nested lapply function?

我有一个向量列表:

this_list <- list(a <- c("this one","that one","these two"),b <- c("those some","heres more","two plus this","and one last one"),c <- c("the final one","it ends here"))
search words <- c("one","two")

我想在列表的每个元素中搜索每个/任何关键字的向量。 我只关心是否出现关键字,而不关心是哪个关键字。

lapply(search_words,grepl,lapply(this_list$,'['))
lapply(search_words,grepl,this_list'a')

这些将分别告诉我列表元素是否有关键字以及矢量元素是否有关键字,by keyword。

我想要一个 function 立即搜索每个列表元素,如果其中有关键字,则每个向量元素。 所需样本 output:

this_list a
search_word "one"
true    true    false
search word "two
false    false    true

this_list b
search_word "one"
false   false   false   true

如果在向量中找到搜索词,则更好的做法是不按 search_word 进行细分,而是按列表元素告诉我

this_list  'a'
true    true    true
this_list 'b'
false    false   true  true
...
sapply(this_list, function(L) 
  sapply(search_words, grepl, x = L, simplify = FALSE),
  simplify = FALSE)
# $a
# $a$one
# [1]  TRUE  TRUE FALSE
# $a$two
# [1] FALSE FALSE  TRUE
# $b
# $b$one
# [1] FALSE FALSE FALSE  TRUE
# $b$two
# [1] FALSE FALSE  TRUE FALSE
# $c
# $c$one
# [1]  TRUE FALSE
# $c$two
# [1] FALSE FALSE

或者

sapply(this_list, function(L)
  rowSums(sapply(search_words, grepl, x = L, simplify = TRUE)) > 0, 
  simplify = FALSE)
# $a
# [1] TRUE TRUE TRUE
# $b
# [1] FALSE FALSE  TRUE  TRUE
# $c
# [1]  TRUE FALSE

仅供参考,切勿在list之类的 function 调用中使用<-

this_list <- list(a <- ..., b <- ...)

这不会命名this_list中的条目,它会在当前环境中生成名为ab的对象,并将这些对象的内容放入没有名称的列表中。

相反,始终在 function 调用中使用= (除非您的意图是创建一个 object 并仅使用对象的内容,忽略名称......这是有效的使用,但不太常见。)

this_list <- list(a = ..., b = ...)

数据

this_list <- list(a = c("this one","that one","these two"),b = c("those some","heres more","two plus this","and one last one"),c = c("the final one","it ends here"))
search_words <- c("one","two")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM