如何将tabyl(x,y)代入R中的函数?

ehxuflar  于 2023-01-22  发布在  其他
关注(0)|答案(2)|浏览(132)

我想创建一个有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.
e1xvtsh3

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。

library(dplyr)
library(janitor)

crTab <- function(df, v1, v2) {
  t <- df %>%
    tabyl({{v1}}, {{v2}})
  return(t)
}

crTab(mtcars, vs, cyl)

vs  4 6  8
  0  1 3 14
  1 10 4  0
pvabu6sv

pvabu6sv2#

如果你想在你的函数中使用带引号的列名作为参数(当与lapply()或类似的组合使用时非常有用),那么你需要如下编写你的函数:

pivot_table_fun = function(arg1, arg2) {
    janitor::tabyl(arg1, !!rlang::sym(arg2))
}

lapply(c("cyl", "gear"), \(x){pivot_table_fun(mtcars, x)})
#> [[1]]
#>  cyl  n percent
#>    4 11 0.34375
#>    6  7 0.21875
#>    8 14 0.43750
#> 
#> [[2]]
#>  gear  n percent
#>     3 15 0.46875
#>     4 12 0.37500
#>     5  5 0.15625

相关问题