[英]How do I apply an index vector over a list of vectors?
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). 我想将长索引向量(50+个非顺序整数)应用于向量的长列表(50个包含100+个名称的字符向量),以便检索特定值(作为列表,向量或数据帧)。
A simplified example is below: 下面是一个简化的示例:
> my.list <- list(c("a","b","c"),c("d","e","f"))
> my.index <- 2:3
Desired Output 期望的输出
[[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?
我在这里错过明显的东西吗?
Thank you, Scott 谢谢你,斯科特
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). 每当遇到类似
lapply
但涉及多个并行列表/向量的问题时,请考虑使用Map
或mapply
( Map
只是对mapply
SIMPLIFY=FALSE
硬编码的mapply
的包装)。
Try this: 尝试这个:
Map("[",my.list,my.index)
#[[1]]
#[1] "b"
#
#[[2]]
#[1] "f"
..or: ..要么:
mapply("[",my.list,my.index)
#[1] "b" "f"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.