You need to enable JavaScript to run this app. 在R中基于Company、Name、Year三列创建指定衍生列的方案求助
优惠活动
大模型
产品
解决方案
定价
更多

在R中基于Company、Name、Year三列创建指定衍生列的方案求助

数据衍生列计算需求

我需要基于数据中的Company、Name、Year三列生成多个衍生列,具体各列的计算规则如下:

  • Number_Years:员工在对应公司的累计任职总年数
  • 7years_Span:从统计当年倒推7年的时间范围内,员工在对应公司的任职年数
  • Continuous_Years:员工在对应公司的连续任职年数
  • Years_Gap:员工本次入职与上一次从该公司离职的间隔年数,无间隔则为0

需基于Company、Name、Year三列,按上述规则生成所有目标衍生列,预期输出结果如下表所示:

CompanyNameYearNumber_Years7years_SpanContinuous_YearsYears_Gap
ABCJohn20027130
ABCJohn20037230
ABCJohn20047330
ABCDave20052110
ABCJohn20067411
ABCDave20072211
ABCJohn20087521
ABCJohn20097520
BBCJim20101110
ABCJim20102120
BBCDave20111110
BBBJohn20111110
ABCJim20112220
ABCJohn20127412

我已尝试自行实现上述逻辑但未取得进展,在相关技术平台检索也未找到适配方案,恳请大家提供实现思路或代码,以下是示例数据的dput结构:

示例数据dput

structure(list(Company = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 3L, 1L, 3L, 2L, 1L, 1L), .Label = c("ABC", "BBB", "BBC"
), class = "factor"), Name = structure(c(3L, 3L, 3L, 1L, 3L, 
1L, 3L, 3L, 2L, 2L, 1L, 3L, 2L, 3L), .Label = c("Dave", "Jim", 
"John"), class = "factor"), Year = c(2002L, 2003L, 2004L, 2005L, 
2006L, 2007L, 2008L, 2009L, 2010L, 2010L, 2011L, 2011L, 2011L, 
2012L), Number_Years = c(7L, 7L, 7L, 2L, 7L, 2L, 7L, 7L, 1L, 
2L, 1L, 1L, 2L, 7L), `7years_span` = c(1L, 2L, 3L, 1L, 4L, 2L, 
5L, 5L, 1L, 1L, 1L, 1L, 2L, 4L), Continuous_Years = c(3L, 3L, 
3L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L), Years_Gap = c(0L, 
0L, 0L, 0L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, 0L, 0L, 2L)), class = "data.frame", row.names = c(NA, 
-14L))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 19:27:03