如何为R语言数据框添加分类变量上次活跃日期列?
为R数据框按类别添加上次活跃日期列
原数据框定义
DF <- data.frame( Date = rep(c("10-12-2024", "10-17-2024", "10-19-2024"), c(4L, 2L, 2L)), category = c("Red", "Red", "Blue", "Blue", "Blue", "Blue", "Red", "Blue") )
原数据内容:
| Date | category |
|---|---|
| 10-12-2024 | Red |
| 10-12-2024 | Red |
| 10-12-2024 | Blue |
| 10-12-2024 | Blue |
| 10-17-2024 | Blue |
| 10-17-2024 | Blue |
| 10-19-2024 | Red |
| 10-19-2024 | Blue |
需求
新增previous active day列,展示对应category的上次活跃日期:
- 同一类别首次出现的日期对应空值
- 后续出现的日期,取该类别上一次出现的不同日期
解决方案
使用dplyr包实现分组处理:
library(dplyr) DF_result <- DF %>% # 将字符型日期转为日期格式,确保排序逻辑正确 mutate(Date = as.Date(Date, format = "%m-%d-%Y")) %>% group_by(category) %>% mutate( # 匹配当前日期对应的上一个活跃日期 prev_date = lag(unique(Date))[match(Date, unique(Date))], # 转换回原字符串格式,空值显示为空 `previous active day` = ifelse(is.na(prev_date), "", format(prev_date, "%m-%d-%Y")) ) %>% ungroup() %>% # 将Date转回原字符格式 mutate(Date = format(Date, "%m-%d-%Y"))
输出结果
| Date | category | previous active day |
|---|---|---|
| 10-12-2024 | Red | |
| 10-12-2024 | Red | |
| 10-12-2024 | Blue | |
| 10-12-2024 | Blue | |
| 10-17-2024 | Blue | 10-12-2024 |
| 10-17-2024 | Blue | 10-12-2024 |
| 10-19-2024 | Red | 10-12-2024 |
| 10-19-2024 | Blue | 10-17-2024 |
内容的提问来源于stack exchange,提问作者FPiper
相关产品推荐
相关产品推荐

