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

R语言按CPSID分组新增家庭人数列并更新教育标识的实现问题

R实现方案

基于dplyr的简洁实现(推荐)

library(dplyr)

Education_status_final <- Education_status %>%
  # 按家庭唯一标识分组,新增家庭总人数列,完全保留原数据行不折叠
  group_by(CPSID) %>%
  mutate(hh_size = n()) %>%
  ungroup() %>%
  # 批量替换4个教育标识列的取值
  mutate(across(c("less than Associate's", "Associate's", "Bachelor's", "more than Bachelor's"),
                ~ .x * hh_size))
  • 分组后调用mutate()生成的hh_size列会自动给同一CPSID的所有行赋值为该家庭的总人数,不会折叠原数据结构
  • 利用原有教育列0/1的取值特性,直接乘以家庭人数:原取值为1的行将替换为家庭人数,原取值为0的行保持0不变,完全匹配需求

基础R实现(无需额外安装包)

# 第一步:统计每个CPSID对应的家庭总人数,匹配回原数据
hh_count <- table(Education_status$CPSID)
Education_status$hh_size <- hh_count[as.character(Education_status$CPSID)]

# 第二步:批量替换教育列取值
edu_cols <- c("less than Associate's", "Associate's", "Bachelor's", "more than Bachelor's")
Education_status[edu_cols] <- Education_status[edu_cols] * Education_status$hh_size

注意事项

你现有代码中生成more than Bachelor's列的部分存在语法错误,判断条件缺失比较运算符,按照分类逻辑应该修改为:

Education_status["more than Bachelor's"] <- ifelse(Education_status$data3.EDUC99 > 15, 1, 0)

否则运行时会报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 16:54:04