如何在矢量列表上应用索引向量? [英] How do I apply an index vector over a list of vectors?
问题描述
我想将一个长索引向量(50+非连续整数)应用于一长列向量(包含100多个名称的50多个字符向量),以便检索特定值(作为列表,向量或数据)帧)。
I want to apply a long index vector (50+ non-sequential integers) to a long list of vectors (50+ character vectors containing 100+ names) in order to retrieve specific values (as a list, vector, or data frame).
简化示例如下:
> my.list <- list(c("a","b","c"),c("d","e","f"))
> my.index <- 2:3
期望输出
[[1]]
[1] "b"
[[2]]
[1] "f"
##or
[1] "b"
[1] "f"
##or
[1] "b" "f"
我知道我可以使用以下每个元素获得相同的值:
I know I can get the same value from each element using:
> lapply(my.list, function(x) x[2])
##or
> lapply(my.list,'[', 2)
我可以从第二个和第三个值中提取每个元素:
I can pull the second and third values from each element by:
> lapply(my.list,'[', my.index)
[[1]]
[1] "b" "c"
[[2]]
[1] "e" "f"
##or
> for(j in my.index) for(i in seq_along(my.list)) print(my.list[[i]][[j]])
[1] "b"
[1] "e"
[1] "c"
[1] "f"
我不知道如何从每个元素中提取一个值。
I don't know how to pull just the one value from each element.
我一直在寻找几天但没有发现任何这样做的例子,但似乎相当直接。我错过了一些明显的东西吗?
I've been looking for a few days and haven't found any examples of this being done, but it seems fairly straight forward. Am I missing something obvious here?
谢谢你,
Scott
Thank you, Scott
推荐答案
每当遇到类似 lapply
的问题但涉及多个并行列表/向量时,请考虑 Map
或 mapply
( Map
只是一个包装 mapply
的包装 SIMPLIFY = FALSE
硬编码。
Whenever you have a problem that is like lapply
but involves multiple parallel lists/vectors, consider Map
or mapply
(Map
simply being a wrapper around mapply
with SIMPLIFY=FALSE
hardcoded).
试试这个:
Map("[",my.list,my.index)
#[[1]]
#[1] "b"
#
#[[2]]
#[1] "f"
..或:
mapply("[",my.list,my.index)
#[1] "b" "f"
这篇关于如何在矢量列表上应用索引向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!