[英]using dplyr::group_by in a function within apply
i'd like to produce nice summaries for a selection of grouping variables in my dataset, where for each group i would show the top 6 frequencies and their associated proportions. 我想为数据集中的一组分组变量生成一个很好的摘要,其中对于每个组,我将显示前6个频率及其相关比例。 I can get this for a single grouping variable using the syntax: 我可以使用以下语法将其用于单个分组变量:
my_db %>%
group_by(my_var) %>%
summarise(n=n()) %>%
mutate(pc=scales::percent(n/sum(n))) %>%
arrange(desc(n)) %>%
head()
How do i modify this expression so it can be used in an apply function? 我如何修改此表达式以便可以在apply函数中使用?
For example using mtcars, I've tried something like this: 例如,使用mtcars,我已经尝试过类似的方法:
apply(mtcars[c(2:4,11)], 2,
function(x) {
group_by(!!x) %>%
summarise(n=n()) %>%
mutate(pc=scales::percent(n/sum(n))) %>%
arrange(desc(n)) %>% head()
}
)
but it doesn't work. 但这不起作用。 Any idea how i can achieve this? 任何想法我怎么能做到这一点?
You should apply using the colnames(dat)
to get the correct groupings: 您应该使用colnames(dat)
以获取正确的分组:
dat <- mtcars[c(2:4,11)]
grp <- function(x) {
group_by(dat,!!as.name(x)) %>%
summarise(n=n()) %>%
mutate(pc=scales::percent(n/sum(n))) %>%
arrange(desc(n)) %>% head()
}
lapply(colnames(dat), grp)
apply(mtcars[c(2:4,11)], 2,
function(x) {
mtcars %>%
group_by(x= !!x) %>%
summarise(n=n()) %>%
mutate(pc=scales::percent(n/sum(n))) %>%
arrange(desc(n)) %>% head()
}
)
you just need the parent df to evaluation 您只需要父级df进行评估
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.