tidyr 包中有一个非常有用的函数uncount,我们可以使用它。首先,我们使用pivot_longer 将年份列移动为行。然后,我们使用uncount,以便每个年龄出现的次数与其出现的次数一样多。然后,group_by 年份并使用summarise 计算汇总统计信息。
library(tidyverse)
dat %>%
pivot_longer(-Age,
names_to = "year",
names_prefix = "X",
values_to = "cnt") %>%
uncount(cnt) %>%
group_by(year) %>%
summarise(q25 = quantile(Age, .25),
q50 = median(Age),
q75 = quantile(Age, .75))
# year q25 q50 q75
# <chr> <dbl> <int> <dbl>
# 1 2000 3 4 5
# 2 2001 4 5 5
# 3 2002 4 5 5.5
这是一个基本的 R 解决方案,使用与 rep 函数类似的想法:
apply(dat[,-1], 2,
FUN = function(x){
rep_age <- rep(dat$Age, x)
c(quantile(rep_age, .25),
quantile(rep_age, .5),
quantile(rep_age, .75))
})
# X2000 X2001 X2002
# 25% 3 4 4.0
# 50% 4 5 5.0
# 75% 5 5 5.5
数据
dat <- structure(list(Age = 2:6,
X2000 = c(4L, 6L, 10L, 8L, 7L),
X2001 = c(1L, 3L, 9L, 9L, 7L),
X2002 = c(2L, 5L, 8L, 8L, 8L)),
class = "data.frame",
row.names = c(NA, -5L))