如何在一个函数中的两个变量中使用tabyl()? [英] How to use tabyl() with two variables within a function?
问题描述
我正在制作两个包含很多变量的表,因此希望编写使用看门人程序包中的tabyl()函数并映射到我感兴趣的变量上.
I'm making two tables that include lots of variables, so am looking to write functions that use tabyl() from the janitor package and map over the variables I'm interested in.
第一个功能运行正常:
cars = datasets::mtcars
first_table = function(variable){
tabyl(variable, show_na = FALSE) %>%
adorn_pct_formatting(digits = 1)
}
first_table(cars$vs)
第二个表的生成方式几乎相同,但应生成两个变量和行百分比的交叉表,而不是代表单个变量的表.这段代码和输出表示我正在尝试使用我的函数进行的操作:
The second table is produced in almost the same way, but should produce the cross-tabs of two variables and row percents instead of a table representing a single variable. This code and output represents what I'm trying to do with my function:
cars %>%
tabyl(vs, am, show_na = FALSE) %>%
adorn_percentages("row") %>%
adorn_pct_formatting(digits = 1) %>%
adorn_ns()
但是,当我将其编写为函数时,tabyl()函数似乎只想识别第一个变量:
When I write this as a function, however, it seems like the tabyl() function only wants to recognize the first variable:
second_table = function(variable1, variable2){
tabyl(variable1, variable2, show_na = FALSE) %>%
adorn_percentages("row") %>%
adorn_pct_formatting(digits = 1) %>%
adorn_ns()
}
second_table(cars$vs, cars$am)
我不太清楚问题出在哪里,我想知道如何编辑此函数,以便为我提供2x2表格,其中包含我可以在没有上述功能的情况下生成的行百分比.
I'm not quite sure what the issue is, and am wondering how I can edit this function to give me the 2x2 table with row percents that I was able to produce without a function above.
非常感谢您的帮助.
推荐答案
而不是传递列值,而是传递未加引号的列名,并使用curl_curly运算符 {{}}
Instead of passing column values, pass the unquoted column names and evaluate with curly_curly operator {{}}
second_table <- function(dat, variable1, variable2){
dat %>%
tabyl({{variable1}}, {{variable2}}, show_na = FALSE) %>%
adorn_percentages("row") %>%
adorn_pct_formatting(digits = 1) %>%
adorn_ns()
}
-测试
second_table(cars, vs, am)
# vs 0 1
# 0 66.7% (12) 33.3% (6)
# 1 50.0% (7) 50.0% (7)
注意:最好也将数据集名称作为参数传递
NOTE: It is better to pass dataset name also as an argument
这篇关于如何在一个函数中的两个变量中使用tabyl()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!