0

I would like to expand a data.frame to include a new column & give this column a dynamically assigned name passed within a function. Here is a simplified example:

passMyName <-function(df, newColTitle) {
  df2 <-data.frame(df, newColTitle = rep(NA, nrow(df)))
  return(df2)
}

randomDF <-data.frame(a=1:3, b=4:6, c=7:9)
passMyName(randomDF, myCustomColTitle)

This will add a new column to the data.frame with the variable name defined by the function, "newColTitle". Instead, I would like to evaluate newColTitle as "myCustomColTitle" and pass this as the named tag for this new column, such that the output data.fram contains a new column called "myCustomColTitle".

Is this possible? Perhaps via substitute(), deparse(), quote(), eval(), paste() etc. You can assume that I've read the following primer on this type of topic (several times actually):

http://adv-r.had.co.nz/Computing-on-the-language.html

But some details have not quite stuck with me.

Thanks

Matt Harper
  • 122
  • 8
raco
  • 67
  • 5

1 Answers1

4

I think this would make much more sense if you passed the new name in as a character value. For example

passMyName <-function(df, newColTitle) {
  df2 <- cbind(df, setNames(list(rep(NA, nrow(df))), newColTitle))
  return(df2)
}

randomDF <-data.frame(a=1:3, b=4:6, c=7:9)
passMyName(randomDF , "myCustomColTitle")

but if you really wanted to use an unevaluated expression, you can use

passMyName <-function(df, newColTitle) {
  newColTitle <- deparse(substitute(newColTitle))
  df2 <- cbind(df, setNames(list(rep(NA, nrow(df))), newColTitle))
  return(df2)
}

randomDF <-data.frame(a=1:3, b=4:6, c=7:9)
passMyName(randomDF, myCustomColTitle)
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • 1
    yes! setName() where have you been all my life? But also, yes, passing a character vector is also the right way to go – raco Jan 29 '15 at 02:03