4

Currently, i have multiple dataframes with the same name and in running order (foo1, foo2, foo3, foo4, foo5... etc). I am trying to create a large dataframe containing all the rows of the above dataframes with rbind(). Is there an elegant way to do it which would be the equivalent of rbind(foo1, foo2, foo3, foo4, foo5...)?

I have tried do.call(rbind, paste0("foo",i)) where i=c(1,2,3...) to no avail.

There is a solution mentioned here, which is: do.matrix <- do.call(rbind, lapply( paste0("variable", 1:10) , get) )

However, the answer mysteriously says "That is the wrong way to handle related items. Better to use a list or dataframe, but you will probably find out why in due course."

Why would that be the wrong way to do this, and what would be the "right" way?

Thanks.

2
  • The mistake they are referring to is creating the individual data frames foo1, foo2, etc in the first place. If you had put them all in a single list in the first place, you can just pass that list to do.call and be done with it. Commented Mar 16, 2015 at 20:55
  • 2
    Very likely you created all those objects through assign. This is not recommended, since you may overwrite other objects and you may not be able to retrieve all the objects effectively. Much better to initialise a list and then set each element of it as one of your data.frames. Anyway, do.call(rbind,mget(paste0("foo",1:N))) should work in your example if N is the number of the data.frames. Commented Mar 16, 2015 at 20:55

1 Answer 1

6

Always try to rigorously capture relations between related instances of data, or related data and methods, or related methods. This generally helps ease aggregate manipulation such as your rbind requirement.

For your case, you should have defined your related data.frames as a single list from the beginning:

foo <- list(data.frame(...), data.frame(...), ... );

And then your requirement could be satisfied thusly:

do.call(rbind, foo );

If it's too late for that, then the solution involving repeated calls to get(), as described in the article to which you linked, can do the job.

Sign up to request clarification or add additional context in comments.

1 Comment

...or mget, which is probably the least inelegant option if one really can't go back and fix the original sin.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.