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

R语言:匹配DataFrame年龄与身高,映射至WHO身高百分位数

解决方案:匹配年龄与身高到WHO百分位数区间

步骤说明

  1. 合并数据:将身高样本数据(df_height)与百分位数阈值数据(df_per)按Age字段关联,确保每个样本能获取对应年龄的所有百分位数阈值。
  2. 判断百分位数区间:通过条件判断,将每个样本的身高与对应年龄的阈值对比,匹配到对应的百分位数区间。
  3. 整理输出:移除冗余的阈值列,保留目标字段。

实现代码(基于dplyr包)

# 若未安装dplyr包,先执行 install.packages("dplyr")
library(dplyr)

# 按Age合并两个数据框
merged_df <- left_join(df_height, df_per, by = "Age")

# 新增Percentile列,判断身高所属区间
result_df <- merged_df %>%
  mutate(Percentile = case_when(
    Height <= P3 ~ "P3",
    Height <= P15 ~ "P15",
    Height <= P50 ~ "P50",
    Height <= P85 ~ "P85",
    TRUE ~ "P97"  # 身高超过P97阈值时归为P97
  )) %>%
  select(Age, Height, Percentile)  # 保留需要的字段

# 输出结果
print(result_df)

运行结果

Age Height Percentile
1   0   49.0        P15
2   1   50.4        P50
3   2   48.8        P15
4   2   51.5        P85
5   4   52.0        P85
6   6   46.8         P3
7   6   49.0        P15

基础R实现方案(无需额外包)

# 合并数据,保留所有身高样本
merged_df <- merge(df_height, df_per, by = "Age", all.x = TRUE)

# 嵌套ifelse判断百分位数区间
merged_df$Percentile <- with(merged_df, 
  ifelse(Height <= P3, "P3",
    ifelse(Height <= P15, "P15",
      ifelse(Height <= P50, "P50",
        ifelse(Height <= P85, "P85", "P97")))))

# 整理结果列
result_df <- merged_df[, c("Age", "Height", "Percentile")]
print(result_df)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 06:57:37