如何获取带/不带阳台公寓租金的均值、中位数及分位数统计量?
按阳台分组获取租金统计量的实现方法
方法1:用dplyr分组计算(推荐,直观灵活)
通过dplyr的分组+汇总功能,可自定义计算需要的所有统计量:
library(dplyr) df %>% group_by(balcony) %>% summarize( 租金均值 = mean(baseRent, na.rm = TRUE), 租金中位数 = median(baseRent, na.rm = TRUE), 25%分位数 = quantile(baseRent, 0.25, na.rm = TRUE), 75%分位数 = quantile(baseRent, 0.75, na.rm = TRUE), 最小值 = min(baseRent, na.rm = TRUE), 最大值 = max(baseRent, na.rm = TRUE) )
- 参数
na.rm = TRUE用于排除缺失值,若你的数据无缺失可省略。
方法2:Base R原生aggregate函数(无需额外包)
不想加载第三方包的话,用base R的aggregate也能实现:
# 直接输出矩阵格式结果 aggregate(baseRent ~ balcony, data = df, FUN = function(x) c( 均值 = mean(x, na.rm = TRUE), 中位数 = median(x, na.rm = TRUE), Q25 = quantile(x, 0.25, na.rm = TRUE), Q75 = quantile(x, 0.75, na.rm = TRUE) )) # 若需转成普通数据框格式 result <- aggregate(baseRent ~ balcony, data = df, FUN = function(x) c( 均值 = mean(x, na.rm = TRUE), 中位数 = median(x, na.rm = TRUE), Q25 = quantile(x, 0.25, na.rm = TRUE), Q75 = quantile(x, 0.75, na.rm = TRUE) )) do.call(data.frame, result)
方法3:psych包一键生成全面统计量
如果需要更完整的统计指标(如标准差、偏度等),用psych包的describeBy:
library(psych) # mat = TRUE 让结果以数据框形式返回 describeBy(df$baseRent, group = df$balcony, mat = TRUE)
输出会包含均值、中位数、分位数、标准差、极值等十余种统计指标。
额外:给箱线图添加数值标注
如果想直接在你已有的箱线图上显示统计量数值,可给ggplot添加stat_summary:
ggplot(df, aes(y = baseRent, x = balcony)) + geom_boxplot() + # 标注中位数 stat_summary(fun = median, geom = "text", aes(label = round(..y.., 2)), vjust = -0.5) + # 标注25%分位数 stat_summary(fun = quantile, fun.args = list(probs = 0.25), geom = "text", aes(label = round(..y.., 2)), vjust = 1.5) + # 标注75%分位数 stat_summary(fun = quantile, fun.args = list(probs = 0.75), geom = "text", aes(label = round(..y.., 2)), vjust = -1.5)
round(..y.., 2)用于保留两位小数,让标注更整洁。
内容的提问来源于stack exchange,提问作者Petziferum
相关产品推荐
相关产品推荐

