Vitalijs Jascisens Vitalijs Jascisens - 11 days ago 8
R Question

extract elements from a list based on a vector of indices

I want to extract elements from a list based on indices stored in a separate vector.

This is my attempt at it:

list_positions<-c(2,3,4)
my_list<-list(c(1,3,4),c(2,3,4,5,6),c(1,2,3,4,6))

my_fun<-function(x,y){
x[y]
}

mapply(my_fun,x=my_list,y=list_positions)


Maybe somebody can suggest a faster solution. My list is has around 14 million elements. I tried parallel solutions, where instead of mapply I used clusterMap but still I would like to have a better performance.

Answer

We may unlist the list, create index based on lengths of 'my_list' and extract the vector

v1 <- unlist(my_list)
p1 <- list_positions
v1[cumsum(lengths(my_list))- (lengths(my_list)-p1)]
#[1] 3 4 4