提问人:Andrew 提问时间:8/2/2023 更新时间:8/2/2023 访问量:32
如何在使用 tidyverse 时在 R 中创建一个函数以接受参数的 NULL 和非 NULL 值?[复制]
how do I create a function in R to accept both NULL and Non-NULL values of parameters when using tidyverse? [duplicate]
问:
我想创建一个函数,如果我在 tibble 中输入分组变量的名称为 NULL,我希望该函数输出 tibble 中整行数。但是,如果我输入分组变量的名称,则输出将是根据分组变量的行数。当我尝试下面的代码时,该函数仅在参数为 NULL 时才有效col_name。如果我输入有效的分组变量,如何使此函数工作?
library(tidyverse)
tib <- tibble(
colB = sample(c("A", "B"), 50, replace = T),
colC = sample(c("C", "D"), 50, replace = T),
colD = sample(c("C", "D"), 50, replace = T)
)
test_fun <- function(df, col_name = NULL, ...){
if(is.null(col_name)){
count(df)
} else
{
y <- enquo(col_name)
z <- enquos(...)
df %>%
count(!!y, !!!z)
}
}
test_fun(df = tib) #- works
test_fun(df = tib, col_name = colB, colC) # does not work
答: 暂无答案
评论