简体   繁体   English

数据框列作为 dplyr R 函数的参数

[英]Data frame column as argument to dplyr R function

I would like to pass a column name as an argument to a function I've created that uses the dplyr package.我想将列名作为参数传递给我创建的使用 dplyr 包的函数。

df = data.frame(grade = c(1,1,1,3,3,5,7,8,8,4),
                score = c(10,20,40,43,56,29,59,37,61,88))

tmp.func = function(df.name, variable.name, year.label){

  require("dplyr")

  df = df.name %>%
    group_by(grade) %>%
    summarise(n = n(),
              M = mean(variable.name),
              SD = sd(variable.name),
              P25 = quantile(variable.name, probs = .25),
              P50 = quantile(variable.name, probs = .50),
              P75 = quantile(variable.name, probs = .75)) %>%
    mutate(grade = as.numeric(as.character(variable.name))) %>%
    arrange(grade) %>%
    dplyr::select(grade,
                  n,
                  M, 
                  SD,
                  P25, 
                  P50, 
                  P75)

  colnames(df) = paste(names(df), ".", year.label, sep = "")

  df

}

tmp = tmp.func(df.name = df, variable.name = "score", year.label = ".1718")

This code results in the below error message.此代码导致以下错误消息。 I have to run this same function dozens of times so I need to create a function that can handle this.我必须多次运行相同的函数,因此我需要创建一个可以处理此问题的函数。 Is there a better way to approach the problem?有没有更好的方法来解决这个问题?

Error in (1 - h) * qs[i] : non-numeric argument to binary operator
In addition: There were 12 warnings (use warnings() to see them)

You can do that with use of enquo and !!您可以使用enquo!! to "unquot" the expression again.再次“取消引用”该表达式。 For more information see this section Different input variable as @svenhalvorson suggested.有关更多信息,请参阅节 @svenhalvorson 建议的不同输入变量

my_summarise2 <- function(df, expr) {
  expr <- enquo(expr)

  summarise(df,
    mean = mean(!! expr),
    sum = sum(!! expr),
    n = n()
  )
}

usage用法

my_summarise2(df, score)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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