[英]Use multiquantile groups from a large dataframe in a grouped dataframe in R
I have the next problem, I have a large dataframe, in which I have to extract the quantiles from a variable but by group, by instance:我有下一个问题,我有一个大数据框,我必须从一个变量中提取分位数,但按组,例如:
list_q <- list()
for (i in 3:5){
tmp <- mtcars %>%
filter(gear == i) %>%
pull(mpg) %>%
quantile(probs = seq(0, 1, 0.25), na.rm = TRUE)
list_q[[i]] <- tmp
}
list_q
With this output:有了这个输出:
[[3]]
0% 25% 50% 75% 100%
10.4 14.5 15.5 18.4 21.5
[[4]]
0% 25% 50% 75% 100%
17.800 21.000 22.800 28.075 33.900
[[5]]
0% 25% 50% 75% 100%
15.0 15.8 19.7 26.0 30.4
Now, I need to group the variable means and determine which quantile it belongs but using the original measures:现在,我需要对变量均值进行分组并确定它属于哪个分位数,但使用原始度量:
a <- mtcars %>%
group_by(gear, carb) %>%
summarize(mpg_mean = mean(mpg)) %>%
ungroup()
gear carb mpg_mean
<dbl> <dbl> <dbl>
1 3 1 20.3
2 3 2 17.2
3 3 3 16.3
4 3 4 12.6
5 4 1 29.1
6 4 2 24.8
7 4 4 19.8
8 5 2 28.2
9 5 4 15.8
10 5 6 19.7
11 5 8 15
So I could do this:所以我可以这样做:
g3 <- a %>%
filter(gear == 3) %>%
mutate(quantile = cut(mpg_mean, list_q[[3]], labels = FALSE, include.lowest = TRUE))
g4 <- a %>%
filter(gear == 4) %>%
mutate(quantile = cut(mpg_mean, list_q[[4]], labels = FALSE, include.lowest = TRUE))
g5 <- a %>%
filter(gear == 5) %>%
mutate(quantile = cut(mpg_mean, list_q[[5]], labels = FALSE, include.lowest = TRUE))
bind_rows(g3, g4, g5)
Obtaining:获得:
# A tibble: 11 x 4
gear carb mpg_mean quantile
<dbl> <dbl> <dbl> <int>
1 3 1 20.3 4
2 3 2 17.2 3
3 3 3 16.3 3
4 3 4 12.6 1
5 4 1 29.1 4
6 4 2 24.8 3
7 4 4 19.8 1
8 5 2 28.2 4
9 5 4 15.8 1
10 5 6 19.7 2
11 5 8 15 1
I wish to know if there is a way to do this more efficiently我想知道是否有办法更有效地做到这一点
We can first group_by
gear
and store the quantiles for mpg
in a list.我们可以首先group_by
gear
并将mpg
的分位数存储在列表中。 We can then also group_by
carb
to get mean
of mpg
value and use the quantiles stored in the list previously to cut
this mean of mpg
column.然后我们还可以group_by
carb
来获得mpg
值的mean
,并使用之前存储在列表中的分位数来cut
mpg
列的平均值。
library(dplyr)
mtcars %>%
group_by(gear) %>%
mutate(gear_q = list(quantile(mpg))) %>%
group_by(carb, add = TRUE) %>%
summarize(mpg_mean = mean(mpg),
gear_q = list(first(gear_q))) %>%
mutate(quantile = cut(mpg_mean, first(gear_q),
labels = FALSE, include.lowest = TRUE)) %>%
select(-gear_q)
# gear carb mpg_mean quantile
# <dbl> <dbl> <dbl> <int>
# 1 3 1 20.3 4
# 2 3 2 17.2 3
# 3 3 3 16.3 3
# 4 3 4 12.6 1
# 5 4 1 29.1 4
# 6 4 2 24.8 3
# 7 4 4 19.8 1
# 8 5 2 28.2 4
# 9 5 4 15.8 1
#10 5 6 19.7 2
#11 5 8 15 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.