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

R语言:如何根据最早日期所在列给新列赋值CH/CL?

需求说明

若数据框res中最早的日期出现在A_returne、B_date、C_returned_date列中,则为新列res$A赋值"CH";若最早日期出现在A_ordered、B_received列中,则赋值"CL"。

数据示例

record_id  inst instance  A_returne     B_date C_returned_date D_returned_date  A_ordered B_received
1         1             NA            2018-10-29      2018-11-10      2021-05-21                       
2         2             NA 2019-11-07                                                                 
3         3             NA 2019-11-08                                                                 
4         4             NA 2019-11-07                                                                 
5         5             NA            2018-11-27      2018-12-12                                       
6         5 rectr        1                                                       2021-01-14 2021-02-17

尝试代码

library(dplyr)
res1 <- res %>%
  mutate(across(where(is.character), \(x) na_if(x, ""))) %>%
  group_by(record_id) %>%
  fill(A_returne, C_returned_date, D_returned_date, .direction="downup", .direction="downup") %>%
  filter(inst == "rectr") %>%
  mutate(oldest_date=pmin(A_returne, C_returned_date, D_returned_date, na.rm=TRUE))

数据结构

res <- structure(list(record_id = c(1L, 2L, 3L, 4L, 5L, 5L), inst = c("", 
"", "", "", "", "rectr"), instance = c(NA, NA, NA, NA, NA, 1L
), A_returne = c("", "2019-11-07", "2019-11-08", "2019-11-07", 
"", ""), B_date = c("2018-10-29", "", "", "", "2018-11-27", ""
), C_returned_date = c("2018-11-10", "", "", "", "2018-12-12", 
""), D_returned_date = c("2021-05-21", "", "", "", "", ""), A_ordered = c("", 
"", "", "", "", "2021-01-14"), B_received = c("", "", "", "", 
"", "2021-02-17")), row.names = c(NA, 6L), class = "data.frame")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 08:47:29