2

I want to rbind a loop that generates data.frames. Here's a [incorrect] loop of the general idea I'm looking for.

for (i in 1:2){
a <- c(2, (i+10))
b <- c((i+10)), 5))
c[i] <- data.frame(a,b)
}
rbind(c)

I want an output like this:

2  11
11  5
2  12
12  5

This question has been asked before, but the answer was a direct solution, with no explanation. I don't know how to read it. It involved do.call and mget.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Andrew
  • 7,201
  • 5
  • 25
  • 34
  • Then I would argue that this question is a dupe. If you don't understand methods of a language, you need to read the documentation. – Mathemats Mar 24 '15 at 23:13
  • 1
    I already read the help file. I still don't understand it. The prior question did not provide reproduceable code. How am I expected to get assistance then? – Andrew Mar 24 '15 at 23:16
  • 1
    maybe [this](http://stackoverflow.com/questions/10801750/whats-the-difference-between-lapply-and-do-call-in-r) is more helpful? `do.call` is useful because you can execute a function by name and pass a list of parameters. forexample, if you wanted to rbind a bunch of data frames that you have in a list, you can do `do.call('rbind', mylistofdataframes)` where hopefully the list was created easily with `lapply` or similar. as another example, `rbind(mtcars, mtcars, mtcars)` and `do.call('rbind', list(mtcars, mtcars, mtcars))` are equivalent – rawr Mar 24 '15 at 23:21
  • the phrasing of your question is slightly hard to understand, could you roll back one and tell us what the aim is? any particular need to use `rbind()` or generate `data.frame`'s? – roman Mar 24 '15 at 23:37
  • @user3115675 Your answer is exactly what I was looking for. Thank you for the help. – Andrew Mar 24 '15 at 23:39
  • Note that this is the slow way to do it. Faster to pre-allocate: http://stackoverflow.com/questions/2908822/speed-up-the-loop-operation-in-r/8474941#8474941 – Ari B. Friedman Mar 25 '15 at 00:22

1 Answers1

10

You don't have to use do.call for this. Just modify the loop as shown below:

out=NULL
for (i in 1:2){
a <- c(2, (i+10))
b <- c((i+10), 5)
c <- data.frame(a,b)
out=rbind(out,c)
}
out
#  a  b
#  2 11
# 11  5
#  2 12
# 12  5

Note: You had a bunch of extra parentheses for the b object. That I also took out.

User7598
  • 1,658
  • 1
  • 15
  • 28