Using variable value as column name in data.frame or cbind

JasonMond picture JasonMond · Mar 29, 2013 · Viewed 8.8k times · Source

Is there a way in R to have a variable evaluated as a column name when creating a data frame (or in similar situations like using cbind)?

For example

a <- "mycol";
d <- data.frame(a=1:10)

this creates a data frame with one column named a rather than mycol.

This is less important than the case that would help me remove quite a few lines from my code:

a <- "mycol";
d <- cbind(some.dataframe, a=some.sequence)

My current code has the tortured:

names(d)[dim(d)[2]] <- a;

which is aesthetically barftastic.

Answer

IRTFM picture IRTFM · Mar 29, 2013
> d <- setNames( data.frame(a=1:10), a)
> d
   mycol
1      1
2      2
3      3
4      4
5      5
6      6
7      7
8      8
9      9
10    10