Fuv8
Fuv8

Reputation: 905

Split a list of data.frames into sublists of data.frames

I have a list of data.frames that looks like:

List          
[[1]]                
    .....               
  List             
   [[2]]            
  ....           

 List              
[[95]]   

I would like to split this long list of data.frames in sublists of 3 data.frames each in order to do other computations in a simple and easy way.

Something like:

sublist1 <- List[1:3]
sublist2 <- List[3:6]
sublist3 <- List[6:9]

and so on.

Upvotes: 3

Views: 1229

Answers (2)

agstudy
agstudy

Reputation: 121568

I would do something like this :

ll <- by(seq_along(l),cut(seq_along(l),3),
                 FUN=function(x)l[x])

Now I have , a list which contains 3 lists. For example to access first sub-lists, you can do :

ll[[1]]
[[1]]
data frame with 0 columns and 0 rows

[[2]]
data frame with 0 columns and 0 rows

[[3]]
data frame with 0 columns and 0 rows

And so on , ll[[2]]...

Upvotes: 3

Arun
Arun

Reputation: 118779

You can use assign and do something like this:

d <- data.frame()
l <- list(d,d,d,d,d,d,d,d,d)

for(i in seq(1, length(l), by=3)) {
    assign(paste0("x", i), l[i:(i+2)])
}

> ls()
# [1] "d"  "i"  "l"  "x1" "x4" "x7"

Upvotes: 2

Related Questions