简体   繁体   English

具有位置向量的向量的子集列表

[英]Subset list of vectors with vector of positions

I have a list of vectors ( mylist ): 我有一个向量列表( mylist ):

a <- c(1,2,3,4)
b <- c(5,6,7,8)
c <- c(9,10,11,12)
mylist <- list(a,b,c)

I also have a vector of positions ( mypos ): 我也有一个位置向量( mypos ):

mypos <- c(1,2,3)

I would like to use mypos to give the position of elements to subset each vector of mypos so that it returns: 我想使用mypos给元素的位置mypos每个向量,以便它返回:

 [1] 1 6 11

I have tried using lapply like this: 我试过像这样使用lapply:

lapply(mylist, "[", mypos) 

but this returns elements 1, 2 and 3 of each vector: 但这会返回每个向量的元素1,2和3:

[[1]]
 [1] 1 2 3

[[2]]
 [1] 5 6 7

[[3]] 
 [1] 9 10 11

I have also tried: 我也尝试过:

lapply(mylist, subset, mypos)

But this returns an error that the subset must be logical 但是这会返回一个错误,该子集必须是逻辑的

We can use Map to extract the corresponding elements of 'mylist' from the index of 'mypos' 我们可以使用Map从'mypos'的索引中提取'mylist'的相应元素

Map(`[`, mylist, mypos)

In the OP's code, the 'mypos' is repeated in each of list elements resulting in extracting all the elements from the index. 在OP的代码中,在每个list元素中重复'mypos',从而从索引中提取所有元素。 Instead it could be looped on sequence 相反,它可以按顺序循环

lapply(seq_along(mylist), function(x) mylist[[x]][mypos[[x]]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM