使用 dplyr,您可以使用 group_by 和 slice 为每个年份值选择前 400 条记录。然后创建分位数,无论是在每年内还是整体上。
set.seed(911) # Simulate some uneven data
df <- data.frame(year=rep(2016:2018, times=c(400,500,600)),
val=rnorm(1500,50,5))
library(dplyr); library(tidyr)
这会在每年内创建分位数
df %>% group_by(year) %>%
slice(1:400) %>%
mutate(q4 = cut(val,
breaks=quantile(val,
probs = seq(0,1,1/4)),
include=TRUE, labels=FALSE)) %>%
# You can stop here and save the output, here I continue to check the counts
count(q4) %>%
pivot_wider(names_from=q4, values_from=n)
# A tibble: 3 x 5
# Groups: year [3]
# year `1` `2` `3` `4`
# <int> <int> <int> <int> <int>
#1 2016 100 100 100 100
#2 2017 100 100 100 100
#3 2018 100 100 100 100
或者您可以取消分组以创建整体分位数(每年的计数会有所不同)。
df %>% group_by(year) %>%
slice(1:400) %>%
ungroup() %>%
mutate(q4 = cut(val,
breaks=quantile(val,
probs = seq(0,1,1/4)),
include=TRUE, labels=FALSE)) %>%
# Stop here to save, or continue to check the counts
group_by(year) %>%
count(q4) %>%
pivot_wider(names_from=q4, values_from=n)
# A tibble: 3 x 5
# Groups: year [3]
# year `1` `2` `3` `4`
# <int> <int> <int> <int> <int>
#1 2016 116 88 102 94
#2 2017 86 114 85 115
#3 2018 98 98 113 91