0

I would like to use an object name as the lhs of an argument to data.frame(), but have it resolve to the string it is assigned. I know how to take a string that has a object name and resolve that string as an object name (here: R: Using object's name to print what is inside the object), but I want to do the reverse. I have a work-around, which is at the bottom of the code snippet, but I have a feeling that there is some usage of eval() and I() or do.call(), or maybe deparse() and substitute() that I am missing.

It is not important now to solve the problem due to the work-around, but now I am really curious because I think the answer to this may illuminate for me some more of the inner workings of R.

Thanks, Matt

h <- "new_col_header"
df <- data.frame(h=1:3)
str(df)

# returns:
# --------
# 'data.frame':    3 obs. of  1 variable:
#  $ h: int  1 2 3
# --------
# But I want the name to be 'new_col_header', not 'h'.


## I can do this to get what I want:
library(plyr)

h <- "new_col_header"
df <- data.frame(x=1:3)
df <- rename(df, c("x" = h))
str(df)

# returns:
# --------
# 'data.frame':    3 obs. of  1 variable:
#  $ new_col_header: int  1 2 3
Community
  • 1
  • 1
mpettis
  • 3,222
  • 4
  • 28
  • 35
  • I'm searching to see if this is a duplicate, but `setNames(data.frame(1:3),h)` will get you there. Also just `colnames(df) <- h` . If you end up using `substitute` `deparse` etc for something that should be simple, you are probably over-thinking it. – thelatemail Oct 06 '14 at 21:59
  • The `setNames` solution looks like a winner in my case. If there isn't a duplicate, and you post that as the solution, I'll accept that. Thanks! – mpettis Oct 06 '14 at 22:06

0 Answers0