我想创建一个有3个参数的函数:df(dataframe)和2个变量。并返回一个交叉表。我可以很容易地使用tabyl
在函数之外完成它。但如何使用一个函数来选择df
和2个变量呢?
我怀疑这是一起不规范评价的案例......
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(janitor)
#>
#> Attaching package: 'janitor'
#> The following objects are masked from 'package:stats':
#>
#> chisq.test, fisher.test
mtcars %>%
janitor::tabyl(vs, cyl)
#> vs 4 6 8
#> 0 1 3 14
#> 1 10 4 0
# How can I put this into a function?
crTab <- function(df, v1, v2) {
t <- df %>%
tabyl(all_of(v1), all_of(v2))
return(t)
}
crTab('mtcars', 'vs', 'cyl')
#> Error in tabyl.default(., all_of(v1), all_of(v2)): The value supplied to the "show_na" argument must be TRUE or FALSE.
#>
#> Did you try to call tabyl on two vectors, like tabyl(data$var1, data$var2) ? To create a two-way tabyl, the two vectors must be in the same data.frame, and the function should be called like this:
#>
#> tabyl(data, var1, var2)
#> or
#> data %>% tabyl(var1, var2).
#>
#> See ?tabyl for more.
2条答案
按热度按时间e1xvtsh31#
如果你想在tidyverse设置中传递列名,请使用双花括号:
“'rlang'使用NSE捕获未计算的参数,然后检查表达式的分析树是否包含两个嵌套的{调用。然后它接受未计算的表达式并对其进行适当的转换。”摘自@Konrad Rudolph https://stackoverflow.com/questions/69454090/how-is-rlangs-curly-curly-operator-implemented#:~:text= The%20curly%2Dcurly%20operator%20%7B%7B,such%20as%20the%20data%20frame。
pvabu6sv2#
如果你想在你的函数中使用带引号的列名作为参数(当与
lapply()
或类似的组合使用时非常有用),那么你需要如下编写你的函数: