简体   繁体   中英

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 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) ).

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

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

Maybe the code below can help...

> sapply(l, function(x) sapply(x, length))
     a b
[1,] 2 5
[2,] 3 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM