[英]Adapting a function to tidyverse ecosystem
Function box_m
from library(rstatix)
currently requires that its first argument NOT include the grouping variable, and its second argument only be the grouping variable.来自
library(rstatix)
的 Function box_m
当前要求其第一个参数不包含分组变量,其第二个参数仅是分组变量。 For example: box_m(d[-1], d$Group)
.例如:
box_m(d[-1], d$Group)
。
I'm trying to re-write this function such that box_m2
would work like: box_m2(d, Group)
.我正在尝试重新编写此 function 以便
box_m2
可以像: box_m2(d, Group)
一样工作。
I have tried the following without success but was wondering if there might be a way to achieve my goal?我尝试了以下但没有成功,但想知道是否有办法实现我的目标?
library(rstatix)
library(tidyverse)
d <- read.csv("https://raw.githubusercontent.com/rnorouzian/v/main/memory.csv")[-1]
box_m(d[-1], d$Group) # How the function currently works
# box_m2(d, Group) # How I would like the function to work
# My trial without success to achieve `box_m2`:
box_m2 <- function(data, group){
dat <- dplyr::select(data, -vars(group))
box_m(dat, one_of(group))
}
# New function
box_m2(d, Group)
You can write the function with the help of curly-curly ( {{}}
) operator.您可以在 curly-curly (
{{}}
) 运算符的帮助下编写 function。
library(rstatix)
library(dplyr)
box_m2 <- function(data, group){
dat <- dplyr::select(data, -{{group}})
box_m(dat, data %>% pull({{group}}))
}
identical(box_m(d[-1], d$Group), box_m2(d, Group))
#[1] TRUE
We could also convert to symbol with ensym
and evaluate ( !!
).我们还可以使用
ensym
转换为符号并计算 ( !!
)。 In that way, it is flexible to either pass unquoted or quoted arguments这样,可以灵活地传递未引用或引用的 arguments
library(rstatix)
library(dplyr)
library(rstatix)
box_m2 <- function(data, group){
group <- ensym(group)
dat <- dplyr::select(data, -!!group)
box_m(dat, data %>%
pull(!! group))
}
-testing -测试
identical(box_m(d[-1], d$Group), box_m2(d, Group))
#[1] TRUE
identical(box_m(d[-1], d$Group), box_m2(d, "Group"))
#[1] TRUE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.