Ben Ben - 1 year ago 86
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.


Answer Source

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:

# [1] 1 2 3
# [1] 4 5 6

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

#   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:

#   y1 y2
# 1  1  4
# 2  2  5
# 3  3  6
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download