根据输入动态更改列名称

时间:2013-04-20 18:00:53

标签: r function dataframe do.call qdap

我试图根据输入动态命名数据框的输出。

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)
}

目前,输出如下:

get.max2(mtcars, mpg)

      name title
Volvo 142E  33.9

但是,我希望它看起来像这样:

get.max2(mtcars, mpg)

      name  mpg
Volvo 142E 33.9

我认为答案与match.call/do.call有关,但在使用这些功能时,我的知识最多是模糊的。有人知道这可能吗?

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

title=..声明在那里是almsot。

你要改为使用:

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

请注意与您所拥有的两个主要区别:

  1. 使用[-(1:2)]代替[1]。来自match.call()的元素是您不想要的函数名称。或者,如果您只想要第二个参数,则可以使用match.call()[3]
  2. 在这种情况下,不需要do.call(.)paste工作得很好。

答案 1 :(得分:0)

您正在寻找?deparse?substitute等内容。

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

variableName(title)
# [1] "title"

variableName(mpg)
# [1] "mpg"

答案 2 :(得分:0)

感谢大家的帮助!我发现的另一种解决方法是在处理后重命名数据框。

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)
}

返回:

get.max2(mtcars, mpg)

      name  mpg
Volvo 142E 33.9
相关问题