我有一个包含3个向量的列表,例如:
> test_list
[[1]]
[1] "a" "b"
[[2]]
[1] "c" "d" "e"
[[3]]
[1] "f" "g"
我想使用包含向量索引的数组访问这些向量的元素,例如:
> indices
[,1] [,2] [,3]
[1,] 1 3 2
[2,] 2 2 2
这是所需的输出:
[,1] [,2] [,3]
[1,] "a" "e" "g"
[2,] "b" "d" "g"
我发现以下方法可以做到:
test_list <- list(c("a", "b"), c("c", "d", "e"), c("f", "g"))
indices <- matrix(c(1, 3, 2, 2, 2, 2), nrow = 2, ncol = 3, byrow = TRUE)
t(apply(indices, 1, function(row){mapply(`[[`, test_list, row)}))
有没有更清洁,更惯用的方式?
一种涉及的选择purrr
可能是:
map2(.x = test_list,
.y = asplit(indices, 2),
~ .x[.y]) %>%
transpose()
[[1]]
[1] "a" "e" "g"
[[2]]
[1] "b" "d" "g"
或base R
使用@nicola提供的注释中的想法的解决方案:
mapply(`[`, test_list, asplit(indices, 2))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句