Vitalijs Jascisens Vitalijs Jascisens - 10 months ago 65
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:




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 Source

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