简体   繁体   中英

Passing an evaluated expression as named arg to function within function (R)

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM