搜索和列表的子集列表

时间:2015-05-26 08:17:23

标签: r

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

示例数据:

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

我想要包含字母&#34; c&#34;的子集列表:

这里获取包含字母&#34; c&#34;:

的最后一个索引节点
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"))))

1 个答案:

答案 0 :(得分:2)

您的第二次修改是在右侧,但您需要使用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"
相关问题