Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_List - Fatal编程技术网

R 返回包含特定字符串的列表的所有元素

R 返回包含特定字符串的列表的所有元素,r,list,R,List,我有一个包含字符串的向量列表,我想让R给我另一个包含所有包含特定字符串的向量的列表。MWE: list1 <- list("a", c("a", "b"), c("a", "b", "c")) list1这应该可以: test <- list("a", c("a", "b"), c("a", "b", "c")) test[sapply(test, function(x) sum(c('a', 'b') %in% x) == 2)] 测试这应该有效: test <- lis

我有一个包含字符串的向量列表,我想让R给我另一个包含所有包含特定字符串的向量的列表。MWE:

list1 <- list("a", c("a", "b"), c("a", "b", "c"))
list1这应该可以:

test <- list("a", c("a", "b"), c("a", "b", "c"))
test[sapply(test, function(x) sum(c('a', 'b') %in% x) == 2)]
测试这应该有效:

test <- list("a", c("a", "b"), c("a", "b", "c"))
test[sapply(test, function(x) sum(c('a', 'b') %in% x) == 2)]

testTry
purr::keep

library(purrr)
keep(list1, ~ all(c("a", "b") %in% .))

试试看
purrr::keep

library(purrr)
keep(list1, ~ all(c("a", "b") %in% .))

我们可以使用
过滤器

Filter(function(x) all(c('a', 'b') %in% x), test)
#[[1]]
#[1] "a" "b"

#[[2]]
#[1] "a" "b" "c"

我们可以使用
过滤器

Filter(function(x) all(c('a', 'b') %in% x), test)
#[[1]]
#[1] "a" "b"

#[[2]]
#[1] "a" "b" "c"

使用
grepl
的解决方案:

> list1[grepl("a", list1) & grepl("b", list1)]
[[1]]
[1] "a" "b"

[[2]]
[1] "a" "b" "c"

使用
grepl
的解决方案:

> list1[grepl("a", list1) & grepl("b", list1)]
[[1]]
[1] "a" "b"

[[2]]
[1] "a" "b" "c"
变量:
function(x)all(c('a','b')%在%x中)
a变量:
function(x)all(c('a','b')%在%x中)