将列名传递给函数 [英] Passing column name into function

查看:56
本文介绍了将列名传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个非标准评估的简单问题:将变量名作为参数传递给函数.

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)`.

reprex软件包(v0.3.0)创建于2020-09-19 sup>

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

我还有一个后续问题.

我还需要 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

reprex软件包(v0.3.0)创建于2020-09-19 sup>

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

推荐答案

您可以使用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

这篇关于将列名传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆