我试图写一个函数,使一个长三路列联表使用group_by和总结从dplyr。我从一个包含3个因素变量的标签开始:年份、乳房x光检查和sp.
> c_table_fn <- function(x){
+ factors %>%
+ group_by(year,mammogram,x) %>%
+ summarize(n = n())}
>
> c_table_fn(sp)
Error: Must group by variables found in `.data`.
* Column `x` is not found
我的函数给出了上面的错误。然而,当我在函数中运行相同的代码时,它运行得很好,并且我得到了所需的表。
> factors %>%
+ group_by(year,mammogram,sp) %>%
+ summarize(n = n())
`summarise()` has grouped output by 'year', 'mammogram'. You can override using the `.groups` argument.
我认为这是由于整洁计算的问题。我尝试将函数中的x更改为{{x}}以及dplyr编程小视频中建议的.data[[x]],但这没有帮助。
我们可以用{{}}
c_table_fn <- function(x){
factors %>%
group_by(year,mammogram,{{x}}) %>%
summarize(n = n())
}
测试
c_table_fn(sp)