1

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 cant figure how to supply arbitrary indeces 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)).

user3375672
  • 3,548
  • 8
  • 37
  • 66

3 Answers3

1

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
akrun
  • 789,025
  • 32
  • 460
  • 575
1

Not using base, but purrr is a great package for lists.

library(purrr)

map_dfc(l, ~lengths(.[1:2]))
# A tibble: 2 x 2
      a     b
  <int> <int>
1     2     5
2     3     6
Adam
  • 7,522
  • 2
  • 11
  • 27
1

Maybe the code below can help...

> sapply(l, function(x) sapply(x, length))
     a b
[1,] 2 5
[2,] 3 6
ThomasIsCoding
  • 80,151
  • 7
  • 17
  • 65