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

在R语言中如何为分组内所有成员添加组内最大出生年份差值?

解决方法

首先修正你原始数据中的长度不匹配问题(id_pers向量长度需与其他列一致,且字符型变量需加引号):

data <- data.frame(id_pers=c(1, 2, 3, 4, 5, 6),
                   Birthyear=c(2018, 2009, 2008, 2000, 1998, 2005),
                   family=c("Elliot", "Elliot", "Elliot", "Gerrard", "Gerrard", "Gerrard")
)

方法一:使用dplyr包(代码直观易读)

加载dplyr包后,按family分组计算出生年份的最大差值,再将差值统一赋值给组内所有成员:

library(dplyr)

datanew <- data %>%
  group_by(family) %>%
  mutate(maxdifference = max(Birthyear) - min(Birthyear)) %>%
  ungroup()

方法二:使用Base R(无需额外安装包)

利用ave()函数实现分组计算逻辑:

datanew <- data
datanew$maxdifference <- ave(datanew$Birthyear, datanew$family, 
                             FUN = function(x) max(x) - min(x))

运行任意一种方法后,得到的datanew数据集与你需求一致:

> datanew
  id_pers Birthyear  family maxdifference
1       1      2018  Elliot            10
2       2      2009  Elliot            10
3       3      2008  Elliot            10
4       4      2000 Gerrard             7
5       5      1998 Gerrard             7
6       6      2005 Gerrard             7

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 19:55:20