Search code examples
rlistnestedsubset

R apply function to nested list elements using "[["


Given a nested list of numeric vectors like l = list( a = list(1:2, 3:5), b = list(6:10, 11:16)). If I want to apply a function, say length, of the "index 1 / first" numeric vectors I can do it using the subset function [[:

> sapply(lapply(l, "[[", 1), length)
a b 
2 5 

I can't figure how to supply arbitrary indices to [[ in order to get length of (in this example) both vectors in every sub-list (a naive try: sapply(lapply(l, "[[", 1:2), length)).


Solution

  • The [[ can only subset a single one. Instead, we need [ for more than 1 and then use lengths

    sapply(lapply(l, "[", 1:2), lengths)
    #     a b
    #[1,] 2 5
    #[2,] 3 6