13

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.

starball
  • 20,030
  • 7
  • 43
  • 238
JasonMond
  • 1,440
  • 1
  • 16
  • 30

4 Answers4

11
> 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
IRTFM
  • 258,963
  • 21
  • 364
  • 487
10

Is structure(data.frame(1:10),names="mycol") aesthetically pleasing to you? :-)

Ferdinand.kraft
  • 12,579
  • 10
  • 47
  • 69
  • I'm one of the upvoters, but I was curious to see if your and my answer would be identical, and see that they are using `dput` and `identical` as tests. – IRTFM Sep 21 '16 at 13:52
2

just use colnames after creation. eg

a <- "mycolA"
b<- "mycolB"
d <- data.frame(a=1:10, b=rnorm(1:10))
colnames(d)<-c(a,b)
d
mycolA     mycolB
 1 -1.5873866
 2 -0.4195322
 3 -0.9511075
 4  0.2259858
 5 -0.6619433
 6  3.4669774
 7  0.4087541
 8 -0.3891437
 9 -1.6163175
 10  0.7642909
Nick
  • 21
  • 1
0

Simple solution:

df <- data.frame(1:5, letters[1:5])
logics <- c(T,T,F,F,T)
cities <- c("Warsaw","London","Paris","NY","Tokio")
m <- as.matrix(logics)
m2 <- as.matrix(cities)
name <- "MyCities"
colnames(m) <- deparse(substitute(logics))
colnames(m2) <- eval(name)
df<-cbind(df,m)
cbind(df,m2)

X1.5 letters.1.5. logics MyCities
1            a   TRUE   Warsaw
2            b   TRUE   London
3            c  FALSE    Paris
4            d  FALSE       NY
5            e   TRUE    Tokio
djneuron
  • 81
  • 4