Ben - 2 months ago 5x
R Question

# How do I make a list of data frames?

How do I make a list of data frames and how do I access each of those data frames from the list? I can't find a simple example of this anywhere.

SO is telling me my post is too short, so I'll get the ball rolling by making a few data frames to be put in a list.

``````d1<-data.frame(y1<-c(1,2,3),y2<-c(4,5,6))
d2<-data.frame(y1<-c(3,2,1),y2<-c(6,5,4))
``````

Answer

This isn't related to your question, but you want to use `=` and not `<-` within the function call. If you use `<-`, you'll end up creating variables `y1` and `y2` in whatever environment you're working in:

``````d1<-data.frame(y1<-c(1,2,3),y2<-c(4,5,6))
y1
# [1] 1 2 3
y2
# [1] 4 5 6
``````

This won't have the seemingly desired effect of creating column names in the data frame:

``````d1
#   y1....c.1..2..3. y2....c.4..5..6.
# 1                1                4
# 2                2                5
# 3                3                6
``````

The `=` operator, on the other hand, will associate your vectors with arguments to `data.frame`.

As for your question, making a list of data frames is easy:

``````d1 <- data.frame(y1=c(1,2,3),y2=c(4,5,6))
d2 <- data.frame(y1=c(3,2,1),y2=c(6,5,4))
my.list <- list(d1, d2)
``````

You access the data frames just like you would access any other list element:

``````my.list[[1]]
#   y1 y2
# 1  1  4
# 2  2  5
# 3  3  6
``````
Source (Stackoverflow)
Comments