1

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!

Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519
maloneypatr
  • 3,562
  • 4
  • 23
  • 33

3 Answers3

1

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.
Ricardo Saporta
  • 54,400
  • 17
  • 144
  • 178
0

You are looking for something like ?deparse and ?substitute.

variableName <- function(x) {
  return(deparse(substitute(x)))
}

variableName(title)
# [1] "title"

variableName(mpg)
# [1] "mpg"
sgibb
  • 25,396
  • 3
  • 68
  • 74
0

Thanks for everyone's help! Another workaround that I discovered was to rename the data frame after processing.

get.max2 <- function(data = NULL, column)
{
  #require(qdap)
  #require(gdata)
  col <- eval(substitute(column), data)
  max <- max(eval(substitute(column), data))
  name <- lookup(col, max, rownames(data))
  name <- name[!is.na(name)]
  df <- data.frame(name = name, title = max(col))
  title2 <- do.call('paste', list(paste(match.call()[3])))
  df <- rename.vars(df, 'title', title2, info = F)
  return(df)
}

Which returns:

get.max2(mtcars, mpg)

      name  mpg
Volvo 142E 33.9
maloneypatr
  • 3,562
  • 4
  • 23
  • 33