You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于cdc数据集男性子集生成指定指标的均值与标准差表格?

问题描述

我正在使用openintro的cdc数据集,需要从已创建的男性子集mdata中生成一个包含**年龄(Age)、身高(Height)、体重(Weight)、期望体重(Desired Weight)**的均值(Mean)和标准差(SD)的表格,目标样式如下:

Mean                  Standard Deviation
Age:              44.27                 16.715
Height:           70.25                 3.009219
Weight:           189.3                 36.55036
Desired Weight:   178.6                 26.25121

已完成子集创建代码:

mdata <- subset(cdc, cdc$gender == ("m"))             
fdata <- subset(cdc, cdc$gender == ("f"))

请问如何生成上述格式的统计表格?

解决方案

方法一:Base R 原生实现

直接针对目标列计算统计量并组合成表格:

# 指定需要计算的目标列(对应数据集中的字段名)
target_cols <- c("age", "height", "weight", "wtdesire")

# 批量计算均值和标准差,忽略缺失值
mean_vals <- sapply(mdata[target_cols], mean, na.rm = TRUE)
sd_vals <- sapply(mdata[target_cols], sd, na.rm = TRUE)

# 组合成数据框并设置行、列名
result_table <- data.frame(
  Mean = mean_vals,
  `Standard Deviation` = sd_vals
)
rownames(result_table) <- c("Age:", "Height:", "Weight:", "Desired Weight:")

# 输出表格
print(result_table)

方法二:tidyverse 工具链实现

如果偏好tidy风格代码,用dplyr+tibble更灵活:

library(dplyr)
library(tibble)

result_table <- mdata %>%
  # 选择目标列
  select(age, height, weight, wtdesire) %>%
  # 批量计算均值和标准差
  summarise(across(everything(), list(Mean = mean, SD = sd), na.rm = TRUE)) %>%
  # 转换为长格式
  pivot_longer(
    everything(),
    names_to = c("Variable", ".value"),
    names_sep = "_"
  ) %>%
  # 替换变量名为目标显示名称
  mutate(Variable = case_when(
    Variable == "age" ~ "Age:",
    Variable == "height" ~ "Height:",
    Variable == "weight" ~ "Weight:",
    Variable == "wtdesire" ~ "Desired Weight:"
  )) %>%
  # 将变量名转为行名
  column_to_rownames("Variable") %>%
  # 重命名标准差列
  rename(`Standard Deviation` = SD)

# 输出表格
print(result_table)

内容的提问来源于stack exchange,提问作者whoami

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 01:15:52