问题
我已经改变了我的问题的表述,因为似乎缺乏明确性。
所以,我们有数千家医院。他们的患者年龄在 0 到 100 岁之间。对于每个年龄,他们都有一定数量的患者,例如医院 1 有 10 名 1 岁的患者,12 名两岁的患者,0 名 100 岁的患者等。
上述数据集是一个小型简化示例,我的实际数据集包含数千家医院和数百万患者的数据。
寻求的结果
我想知道每家医院的患者年龄中位数。
到目前为止的解决方案
展开表格,使每个患者的年龄有一个单独的行,然后取中位数。这将导致我的表有数亿行,所以是不可取的。
library(dplyr)
## table
hospital <- c(rep(1:3, each = 10))
patient_age <- c(rep(seq(0, 90, by = 10), 3))
number_patients <- round(runif(30, 0, 100),0)
df <- bind_cols(hospital, patient_age, number_patients)
colnames(df) <- c("hospital", "patient_age", "number_patients")
## my impractical solution
df1 <- filter(df, hospital == 1)
df1a <- rep(df1$patient_age, df1$number_patients)
median(df1a)
## there's no way I can repeat this for each hospital (there are 1000s)