Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new list starting from the list elements of another list (nested lists)

Tags:

list

r

in my dataset LISTS is a list of lists. Suppose it is composed by 3 lists, each of those made up by 3 matrices. Hence I have 9 matrices in total:

A <- list(matrix(rep(1.1,4),ncol=2), 
          matrix(rep(1.2,4),ncol=2), 
          matrix(rep(1.3,4),ncol=2))

B <- list(matrix(rep(2.1,4),ncol=2),
          matrix(rep(2.2,4),ncol=2), 
          matrix(rep(2.3,4),ncol=2))

C <- list(matrix(rep(3.1,4),ncol=2),
          matrix(rep(3.2,4),ncol=2),
          matrix(rep(3.3,4),ncol=2))

LIST <- list(A,B,C)

What I need to do is to create a new list composed by three lists. The first one made up by the lower-level matrices A[[1]], B[[1]], C[[1]]; the second by A[[2]], B[[2]], C[[2]], and the last one by A[[3]], B[[3]], C[[3]].

At first I tried to isolate single matrices with, for instance, LIST[[1]][[1]] and so on. This works, but then I didn't find the corret syntax for selecting 3 matrices at one time. What I mean (with wrong syntax) is to select the first matrix of each list by using something like LIST[(1:3)][[1]], which is clearly wrong...

In other words, I am wondering whether there is a direct way for selecting a subset of a nested list (similarly to what it is possible to do with matrices or dataframes)

Thank you very much for any help!

like image 893
Stefano Lombardi Avatar asked Dec 04 '25 10:12

Stefano Lombardi


1 Answers

Perhaps you are just looking for [[ within lapply, but your question is not very clear.

For example, to get the third element from each of the sublists:

lapply(LIST, `[[`, 3)
# [[1]]
#      [,1] [,2]
# [1,]  1.3  1.3
# [2,]  1.3  1.3
# 
# [[2]]
#      [,1] [,2]
# [1,]  2.3  2.3
# [2,]  2.3  2.3
# 
# [[3]]
#      [,1] [,2]
# [1,]  3.3  3.3
# [2,]  3.3  3.3
like image 191
A5C1D2H2I1M1N2O1R2T1 Avatar answered Dec 07 '25 01:12

A5C1D2H2I1M1N2O1R2T1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!