在R中的宏(函数)中未找到的对象 [英] object not found in summarise with macro(function) in r

查看:115
本文介绍了在R中的宏(函数)中未找到的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用函数 dplyr 创建宏。

I'm trying make macro with function and dplyr.

我想做的是 summary 特定变量。在函数中,变量为 i 。年龄在数据集中

What I'm trying to do is summarise specific variable. In function, the variable is i. the age is in the dataset

fun<-function(i){
dataset%>%dplyr::summarise(t1=mean(i),t2=sd(i))
}
fun(i=age)

当我执行 summaryise 而没有函数,它起作用了。但是,使用函数时,出现错误。

When I executed summarise without function, it worked. However, with function, the error appeared.

 Error in .f(.x[[i]], ...) : object 'age' not found 

Can有人帮我知道问题出在哪里吗?

Can anybody help me know what was the problem?

推荐答案

我们可以使用 {{}} 运算符,以评估传递给函数的未加引号的列名

We can use the {{}} operator to evaluate the unquoted column name passed into the function

library(dplyr)
library(rlang)
fun<-function(datasset, i){
   dataset%>%
        dplyr::summarise(t1=mean({{i}}),
                         t2=sd({{i}})
 }
fun(dataset, age)






或者另一个选择是使用 enquo 进行评估( !! ]

fun<-function(dataset, i){
   i <- enquo(i)
   dataset%>%
        dplyr::summarise(t1=mean(!!i),
                         t2=sd(!!i))
 }
fun(dataset, age)

注意:这可能最好将数据对象以及参数传递给函数

NOTE: It may be better to pass the data object as well as argument to function

这篇关于在R中的宏(函数)中未找到的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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