I have a list structure which represents a table being handed to me like this
> l = list(list(1, 4), list(2, 5), list(3, 6))
> str(l)
List of 3
$ :Lis
The sapply
extracts the ith element of each component of l
creating a numeric vector and the lapply
applies it over 1:2 (since there are k=2 elements in each component of l
).
If you know that k is 2 then the first line could be replaced with k <- 2
. Also note that in the first line we divide by max(..., 1) to avoid dividing by 0 in the case that l
is a zero length list.
The code below gives the output shown in the question; however, the subject refers to nested lists and if we wanted a list of lists rather than a list of numeric vectors then we could replace sapply
with lapply
.
k <- length(unlist(l)) / max(length(l) , 1)
lapply(seq_len(k), function(i) sapply(l, "[[", i))
giving:
[[1]]
[1] 1 2 3
[[2]]
[1] 4 5 6