简体   繁体   中英

lapply with different indices in list of lists

I'm trying to get the output of a certain column ( $new_age = numeric values ) within lists of lists.

Data is "my_groups", which consists of 28 lists. Those lists have lists themselves of irregular size:

92 105 96 86 91 94 73 100 87 89 88 90 112 82 95 83 94 106 91 101 86 81 89 68 89 87 109 73 (len_df)

The 1st list has 92 lists, the 2nd 105 etc. ... until the 28th list with 73 lists.

First, I want my function to iterate through the 28 years of data and second, within these years I want to iterate through len_df , since $new_age is in the nested lists.

What I tried is this:

test <- lapply(seq(1:28), function(i) sapply(seq(1:len_df), function(j) (my_groups[[i]][[j]]$new_age) ) )

However, the index is out of bounds and I'm not sure how to combine two different indices for the nested lists. Unlist is not ideal, since I have to treat the data as separate groups and sorted for each year.

Expected output: $new_age (numeric values) for each of the 28 years eg 1st = 92 values, 2nd = 105 values etc.

Any idea how to make this work? Thank you!

Here are a few different approaches:

1) whole object approach Assuming that the input is L shown reproducibly in the Note at the end and that what is wanted is a list of length(L) numeric vectors, ie list(1:2, 3:5) , consisting of the new_age values:

lapply(L, sapply, `[[`, "new_age")

giving:

[[1]]
[1] 1 2

[[2]]
[1] 3 4 5

2) indices If you want to do it using indices, as in the code shown in question, then using seq_along :

ix <- seq_along(L)
lapply(ix, function(i) sapply(seq_along(L[[i]]), function(j) L[[i]][[j]]$new_age))

3) unlist To use unlist form an appropriate grouping variable using rep and split into separate vectors by it. This assumes that new_age are the only leaves which may or may not be the case in your data but is the case in the reproducible example in the Note at the end.

split(unname(unlist(L)), rep(seq_along(L), lengths(L)))

Note

L <- list(list(list(new_age = 1), list(new_age = 2)),
  list(list(new_age = 3), list(new_age = 4), list(new_age = 5)))

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