每人观察值的中位数

时间:2019-07-02 14:29:03

标签: r dplyr data-manipulation longitudinal

我有一个长格式的数据框,显示了一组个人的身高的重复测量。

平均观察次数是2000/500 =每个孩子4次观察。

如何计算每个孩子的观察次数的中位数和四分位数范围?

data <- data.frame(

child_id = 1:500,
height_1 = rnorm(500, mean = 80, sd = 2),
height_2 = rnorm(500, mean = 90, sd = 2),
height_3 = rnorm(500, mean = 100, sd = 2),
height_4 = rnorm(500, mean = 115, sd = 2)
)

data_long <- reshape(data, varying=c(
"height_1", "height_2", "height_3", "height_4"),
direction= "long", idvar="child_id", timevar = "time", sep="_"
)

# Mean observation per child = 2000/500 = 4
data_long$id_f <- as.factor(data_long$child_id)
length(unique(data_long$id_f)) # 500 children

length(data_long$height) # 2000 observations

1 个答案:

答案 0 :(得分:-1)

我们可以使用dplyr。按“ child_id”分组,获取“高度”列的medianIQR

library(dplyr)
data_long %>% 
   group_by(child_id) %>%
   summarise(median = median(height),
            interQuartileRange = IQR(height))

如果我们希望基于观察值的数字medianIQR

data_long %>%
  count(child_id) %>% 
  summarise(median = median(n), IQR = IQR(n))