繁体   English   中英

搜索和列表的子集列表

[英]Search and subset list of lists

我搜索了SO但找不到相关的答案。

样本数据:

example.list <- list(list("a",list("b"),list("c")),list("c"))

我想要包含字母“c”的子集列表:

这里获取包含字母“c”的最后一个索引节点:

check.a <- lapply(example.list, function(x) grep("c",x))

我将如何获得上述索引的列表? 或者如何获得列表清单?

获得列表c(1,3)的最后节点的一部分存在于列表节点c(1,2)之前。

编辑:所需的输出:(像这样)

 [[1]][[3]]
 [[1]][[3]][[1]]
 [1] "c"


 [[2]]
 [[2]][[1]]
 [1] "c"

但是我需要的是还要了解提供的索引,如何获得嵌套列表的子集? 请使用check.a

编辑2:

以下是可用于对相关列表节点进行子集化的列表索引:

first.list.index <- which(lapply(lapply(example.list, function(x) grep("c",x)),length)>0)
last.list.index <- unlist(lapply(example.list, function(x) grep("c",x)))

这个想法是这样的:(不工作,只是为了展示我所追求的)

lapply(list(a=first.list.index,b=last.list.index), function(a,b) example.list[[a]][[b]])

编辑3 :(最后编辑)

实际数据看起来像这样:(我希望通过我提供的索引解决方案,这就是为什么我减少了问题)

 [[1]]
 [[1]][[1]]
 [1] "a"

 [[1]][[1]]$data

 [[1]][[2]]
 [[1]][[2]][[1]]
 [1] "b"

 [[1]][[1]]$data

 [[1]][[3]]
 [[1]][[3]][[1]]
 [1] "c"

 [[1]][[1]]$data


[[2]]
[[2]][[1]]
 [1] "c"

[[2]][[1]]$data

抱歉这个烂摊子!

这是减少的输入:

     list(list(structure(list(name = "a", data = c("21016954")), .Names = c("name", "data"
     )), structure(list(name = "b", data = c("17103795")), .Names = c("name", "data")), structure(list(name = "c", 
     data = c("38036543")), .Names = c("name", "data"))),   list(structure(list(name = "c", data = c("42456597")), .Names =   c("name","data"))))

您的第二次编辑沿着右侧行,但您需要使用Map而不是lapply 使用您的数据

d <-  list(list(structure(list(name = "a", data = c("21016954")), .Names = c("name", "data"
    )), structure(list(name = "b", data = c("17103795")), .Names = c("name", "data")), structure(list(name = "c", 
    data = c("38036543")), .Names = c("name", "data"))),   list(structure(list(name = "c", data = c("42456597")), .Names =   c("name","data"))))

Map(function(i, j) d[[i]][[j]], 
    i = which(lapply(lapply(d, function(x) grep("c",x)),length)>0), 
    j = unlist(lapply(d, function(x) grep("c",x))))

#[[1]]
#[[1]]$name
#[1] "c"
#
#[[1]]$data
#[1] "38036543"
#
#
#[[2]]
#[[2]]$name
#[1] "c"
#
#[[2]]$data
#[1] "42456597"

暂无
暂无

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

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