How can I automatically list the columns in rbind?

I often rewrite vectors with the same variables:

v1 = 1
v2 = 2
rbind(c(v1, v2), c(v1, v2))
     [,1] [,2]
[1,]    1    2
[2,]    1    2

      

I know I can specify vector columns explicitly, but this is rather tedious and redundant when you have a lot of variables:

rbind(c(v1 = v1, v2 = v2), c(v1= v1, v2 = v2))
     v1 v1
[1,]  1  2
[2,]  1  2

      

How can I tell rbind () to use variable names to refer to each column?

+3


source to share


2 answers


You can use a combination of rbind

and mget

:

v1 <- 1
v2 <- 2

rbind(mget(c("v1", "v2")), mget(c("v1", "v2")))

      

mget

will search environment for variables with specified names. Most importantly, the result will be the named object list

.



However, I think a cleaner solution is to simply do data.frame

as suggested above:

rbind(data.frame(v1, v2), data.frame(v1, v2))

      

+2


source


You only need to specify the elements in the first vector passed to rbind

:

v1 <- 1
v2 <- 2
rbind(c(v1=v1, v2=v2), c(v1, v2), c(4, 5))
#      v1 v2
# [1,]  1  2
# [2,]  1  2
# [3,]  4  5

      



I am assuming that the example you gave was simplified and that you do not plan on repeating the same line over and over; if so, there are easier ways than typing a string many times (for example, using replicate

or rep

).

+5


source







All Articles