combining rbind and lapply -- the reasoning behind not using them together In the book, applying functions to lists section, we learn about do.call and lapply by using the function rbind.
It says: It makes no sense to combine rbind and lapply.
Is this because rbind doesn't work if we use lapply? It's supposed to stack things together, right? Well it's not doing that in the lapply
example at all, it's leaving things the way they were.
Answers and follow-up questions Answer or follow-up question 1
It makes no sense to combine rbind and lapply, because lapply will apply rbind to each element of the list separately. If there are five
elements in the list, rbind will be applied five times, once to each element. lapply is a replacement for a loop. You want to use do.call
do.call applies the function that you supply it with once (in this case rbind), and uses the list with data frames as the arguments of that
Suppose l is a list with three data frames, then
do.call(rbind,l) is equivalent to rbind(l[],l[],l[])
lapply(l,rbind) is equivalent to list(rbind(l[]),rbind(l[]),rbind(l[])
Note that list(rbind(l[]),rbind(l[]),rbind(l[]) is equivalent to list(l[],l[],l[]), and therefore equivalent to l.
Michel BallingsSign in to be able to add an answer or mark this question as resolved.