在R

时间:2017-06-02 22:03:06

标签: r list

作为一个玩具示例,假设我有一个list.map,其主索引包含子索引,这些索引是指向两个元素的某个向量的“指针”。给定test列表只包含每个主索引的“指针”索引,我想有一个输出相应向量的最终列表。

list1=list(c(1,2),c(3,4),c(5,6))
list.map=list(list1,list1)
test=list(c(1,3),2)

> list.map
[[1]]
[[1]][[1]]
[1] 1 2

[[1]][[2]]
[1] 3 4

[[1]][[3]]
[1] 5 6


[[2]]
[[2]][[1]]
[1] 1 2

[[2]][[2]]
[1] 3 4

[[2]][[3]]
[1] 5 6

> test
[[1]]
[1] 1 3

[[2]]
[1] 2

我的尝试

test.out=NULL
for(b in c(1,2)){
  test.out[[b]]=as.vector(sapply(test[[b]],function(x) list.map[[b]][[x]]))
}

> test.out
[[1]]
[1] 1 2 5 6

[[2]]
[1] 3 4

这不是最优雅的方法,理想情况下,我的b循环中有for索引的数百个主索引。有没有更好的方法来写这个?

2 个答案:

答案 0 :(得分:2)

Map(function(x, y) unlist(x[y]), list.map, test)

[[1]]
[1] 1 2 5 6

[[2]]
[1] 3 4

答案 1 :(得分:1)

tidyverse语法为

library(tidyverse)
map2(list.map, test, `[`) %>%
                  map(unlist)
#[[1]]
#[1] 1 2 5 6

#[[2]]
#[1] 3 4
相关问题