我正在使用来自库(摘要工具)的freq来创建一些频率。
示例:
mtcars %>%
freq(mpg,
cumul = FALSE,
totals = TRUE)我正在尝试创建一个用户函数,这样我就可以遍历select变量来生成这些表:
create_freq <- function(v1) {
v1 <- enquo(v1)
out <- mtcars %>%
freq(!!v1,
cumul = FALSE,
totals = TRUE)
return(out)
}
create_freq(mpg)但是我得到了这个错误,我不能确定,我认为闭包是不正确的,但我不知道如何调试...帮帮忙好吗?
Error in freq(., !!v1, cumul = FALSE, totals = TRUE) :
NULL is either NULL or does not exist
Called from: freq(., !!v1, cumul = FALSE, totals = TRUE)发布于 2021-09-10 04:31:20
mtcars %>%freq(mpg,cumul = FALSE,totals = TRUE)给出了与freq(mtcars$mpg, cumul = FALSE, totals = TRUE相同的输出。因此,在不使NSE变得复杂的情况下,您可以尝试。
library(summarytools)
create_freq <- function(v1) {
freq(v1,cumul = FALSE, totals = TRUE)
}对于一个变量-
create_freq(mtcars$mpg)对于多个变量-
lapply(mtcars[1:2], create_freq)发布于 2021-09-10 04:26:54
我不知道这个函数,但从我搜索的结果来看,它会给出类似的结果:
库
library(dplyr)函数
create_freq <- function(df,grp_var){
df %>%
count({{grp_var}} := as.character({{grp_var}})) %>%
mutate("%" = 100*n/sum(n)) %>%
{. ->>temp} %>%
bind_rows(
temp %>%
group_by({{grp_var}} := "Total") %>%
summarise(across(.cols = where(is.numeric),.fns = sum))
)
}示例
create_freq(mpg,cyl)
cyl n `%`
<chr> <int> <dbl>
1 4 81 34.6
2 5 4 1.71
3 6 79 33.8
4 8 70 29.9
5 Total 234 100 https://stackoverflow.com/questions/69127168
复制相似问题