r - 如何用R中的频率表获得中位数?

标签 r median frequency-table

问题

我更改了问题的表述方式,因为问题似乎不够清晰。

所以,我们有数千家医院。他们的患者年龄在 0 岁到 100 岁之间。对于每个年龄段,他们都有一定数量的患者,例如Hospital1 有 10 名 1 岁患者、12 名 2 岁患者、0 名 100 岁患者等。

enter image description here

上面的数据集是一个简单的小例子,我的实际数据集包含数千家医院和数百万患者的数据。

寻求结果

我想知道每家医院的患者年龄中位数。

目前的解决方案

展开表格,以便每个患者的年龄都有一个单独的行,然后取中位数。这将导致我的表有数亿行,因此是不可取的。

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) 

最佳答案

编辑:

以下是按医院计算患者平均年龄的方法:

df %>%
  group_by(hospital) %>%
  summarise(
    mean_age = sum(patient_age*number_patients)/sum(number_patients)
    )

或者简单地说:

df %>%
  group_by(hospital) %>%
  summarise(
    mean_age = mean(rep(patient_age,number_patients))
  )

这是中位数:

df %>%
  group_by(hospital) %>%
  summarise(
    median_age = sort(rep(patient_age,number_patients))[length(rep(patient_age,number_patients))/2]
  )

在这里,我们子集 sort(rep(patient_age,number_patients))其中间值,即 length(rep(patient_age,number_patients))/2

编辑 2:

或者简单地说:

df %>%
  group_by(hospital) %>%
  summarise(
    median_age = median(rep(patient_age,number_patients))
  )

关于r - 如何用R中的频率表获得中位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67569006/

相关文章:

r - 控制台和 Rmarkdown 的准确度结果不同

r - 图像与 ggplot : how to plot color legend?

MySQL:计算按列分组的值的中值

随着时间的推移构建子集的滚动中位数

mysql - 获取 6 个表的中位数

pandas - 如何从频率表创建箱线图

r - 如何在R中使用glmnet计算套索回归的R平方值

r - RMarkdown 演示文稿中的列中的代码