问题描述
我有一个非标准评估的简单问题:将变量名作为参数传递给函数.
I have a simple problem with non-standard evaluation: passing a variable name as an argument into a function.
作为一个可重现的示例,这很简单:从 mtcars
数据集中取一个变量 mpg
的平均值.我的最终目标是要有一个函数,可以在其中输入数据集和变量,并获取均值.
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.
因此没有功能:
library(tidyverse)
mtcars %>% summarise(mean = mean(mpg))
#> mean
#> 1 20.09062
我尝试使用 get()
进行非标准评估,但出现错误:
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)`.
我还有一个后续问题.
我还需要 variable
参数作为 char
字符串,我尝试了下面的代码,但是我仍然不知道该怎么做:
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
推荐答案
您可以使用curl-curly( {{}}
)运算符将列名作为未加引号的变量传递.
You could use the curly-curly ({{}}
) operator to pass column name as unquoted variable.
要获取作为字符值传递的变量,我们可以使用 deparse
, substitute
.
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
这篇关于将列名传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!