Robert Kubrick
Robert Kubrick

Reputation: 8713

How can I automatically name columns in rbind?

I often rbind 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 explicitly name the vector columns, but it's rather tedious and redundant when you have many variables:

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

How can I instruct rbind() to use the variable names to name each column?

Upvotes: 3

Views: 2552

Answers (2)

sdgfsdh
sdgfsdh

Reputation: 37065

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 the environment for variables with the given names. Most importantly, the result is a named list object.

However, I think a cleaner solution is to just make a data.frame, as suggested above:

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

Upvotes: 2

josliber
josliber

Reputation: 44330

You only need to name 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'm assuming the example you provide was simplified and you're not planning on repeating the same row many times; if so, there are easier ways than typing the row a lot of times (e.g. using replicate or rep).

Upvotes: 5

Related Questions