Search code examples
rfunctiondataframedo.callqdap

Dynamically change column names based on inputs


I am trying to dynamically name the output of a data frame based upon the inputs.

get.max2 <- function(data = NULL, column)
{
  #require(qdap)
  col <- eval(substitute(column), data)
  max <- max(eval(substitute(column), data))
  name <- lookup(col, max, rownames(data))
  name <- name[!is.na(name)]
  #title <- do.call('paste', list(paste(match.call()[1])))
  df <- data.frame(name = name, title = max(col))
  print(df)
}

Currently, the output looks like this:

get.max2(mtcars, mpg)

      name title
Volvo 142E  33.9

But, I want it to look like this:

get.max2(mtcars, mpg)

      name  mpg
Volvo 142E 33.9

I think the answer has something to do with match.call/do.call, but my knowledge is fuzzy at best when using these functions. Anyone know if this possible?

Thanks for your help!


Solution

  • you're title=.. statement is almsot there.

    you want to use instead:

     title = paste(match.call()[-(1:2)], collapse=" ")   
     # the collapse argument is optional, it's not clear
     #    how you would like to handle multiple arguments
    

    Notice the two main differences from what you had:

    1. using [-(1:2)] instead of [1]. The element from match.call() is the function name, which you do not want. Alternatively, you can use match.call()[3] if you want just the second argument.
    2. In this situation, there is no need for do.call(.). paste works just fine.