[英]Passing column name into function
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.作为一个可重复的例子,这里有一个简单的事情:从
mtcars
数据集中取一个变量mpg
的mtcars
。 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:我尝试使用
get()
进行非标准评估,但出现错误:
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)由reprex 包(v0.3.0) 于 2020 年 9 月 19 日创建
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:我还需要将
variable
参数作为char
字符串,我尝试了下面的代码,但我仍然缺少如何做到这一点:
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)由reprex 包(v0.3.0) 于 2020 年 9 月 19 日创建
You could use the curly-curly ( {{}}
) operator to pass column name as unquoted variable.您可以使用 curl-curly (
{{}}
) 运算符将列名作为未加引号的变量传递。
To get variables passed as character value we can use deparse
, substitute
.为了获得尽可能字符值,我们可以使用传递变量
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.