Passing column name into function

两盒软妹~` 提交于 2021-02-04 21:05:59

问题


I have a simple problem with non-standard evaluation: passing a variable name as an argument into a function.

As a reproducible example, here's a simple thing: taking the mean of one variable, mpg from the mtcars dataset. My end goal is to have a function where I can input the dataset and the variable, and get the mean.

So without a function:

library(tidyverse)
mtcars %>% summarise(mean = mean(mpg))

#>       mean
#> 1 20.09062

I've tried to use get() for non-standard evaluation, but I'm getting errors:

library(tidyverse)
summary_stats <- function(variable, dataframe){
  dataframe %>% summarise(mean = get(variable))
}

summary_stats(mpg, mtcars)

#> Error: Problem with `summarise()` input `mean`.
#> x invalid first argument
#> ℹ Input `mean` is `get(variable)`.

Created on 2020-09-19 by the reprex package (v0.3.0)

Edit:

I also had one additional follow-up question.

I also need the variable argument as a char string, I tried the code below, but I'm still missing how to do that:

library(tidyverse)
summary_stats <- function(variable, dataframe){
  dataframe %>% summarise(mean = mean({{variable}}))
  print(as.character({{variable}}))
}

summary_stats(disp, mtcars)
#> Error in print(as.character({: object 'disp' not found

Created on 2020-09-19 by the reprex package (v0.3.0)


回答1:


You could use the curly-curly ({{}}) operator to pass column name as unquoted variable.

To get variables passed as character value we can use deparse, substitute.

library(dplyr)
library(rlang)

summary_stats <- function(variable, dataframe){
  print(deparse(substitute(variable)))
  dataframe %>% summarise(mean = mean({{variable}}))
}
#[1] "mpg"

#      mean
#1 20.09062


来源:https://stackoverflow.com/questions/63964999/passing-column-name-into-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!