Using cbind on an arbitrarily long list of objects

rtyro picture rtyro · Apr 4, 2011 · Viewed 30k times · Source

I would like to find a way to create a data.frame by using cbind() to join together many separate objects. For example, if A, B, C & D are all vectors of equal length, one can create data.frame ABCD with

ABCD <- cbind(A,B,C,D)

However, when the number of objects to be combined gets large, it becomes tedious to type out all of their names. Furthermore, Is there a way to call cbind() on a vector of object names, e.g.

objs <- c("A", "B", "C", "D")
ABCD <- cbind(objs)

or on a list containing all the objects to be combined, e.g.

obj.list <- list(A,B,C,D)
ABCD <- cbind(obj.list)

Currently, the only workaround I can think of is to use paste(), cat(), write.table(), and source() to construct the arguments to cbind(), write it as a script and source it. This seems like a very nasty kludge. Also, I have looked into do.call() but can't seem to find a way to accomplish what I want with it.

Answer

Prasad Chalasani picture Prasad Chalasani · Apr 4, 2011

The do.call function is very useful here:

A <- 1:10
B <- 11:20
C <- 20:11

> do.call(cbind, list(A,B,C))
      [,1] [,2] [,3]
 [1,]    1   11   20
 [2,]    2   12   19
 [3,]    3   13   18
 [4,]    4   14   17
 [5,]    5   15   16
 [6,]    6   16   15
 [7,]    7   17   14
 [8,]    8   18   13
 [9,]    9   19   12
[10,]   10   20   11