thothal thothal - 4 months ago 15
R Question

Indexing lists of list/vectors


lst <- list(1, 1:3, 2:4)
ind <- c(1, 2, 2)


I can guarantee that
length(ind) == length(lst)
and now I want to get the 1st element of the the first element of
, then the second element of the second element and finally the second element of the third element.

With a loop I could do something like

sapply(seq_along(ind), function(i) lst[[i]][[ind[i]]])

So my question is whether I need the loop or is there any smart indexing technique which I am not aware of? Background of the question is that I have the impression that I do not make best use of
capability to do incredible stuff with smart indexing (like indexing a matrix with another matrix).


We can use mapply to get the corresponding element of 'lst' based on the index in 'ind'.

mapply(`[`, lst, ind)
#[1] 1 2 3