将匹配日期替换为 R 中重复行中的对应日期

问题描述 投票:0回答:1

在以下数据中,我想将任何值为“6/1/2020”的 GrDate 替换为同一个人的相应 GrDate 值(Nb)。

因此,对于 Nb = 100,我想将“6/1/2020”替换为“10/20/2019”。

200 可以,没有“6/1/2020”日期。

对于Nb=300,我想替换“6/1/2020”“7/29/2018”。

最好的 R 逻辑是什么

# Load required library
library(lubridate)

# Create the data frame
df <- data.frame(
 Nb = c(100, 100, 200, 200, 300, 300),
 Name = c("Peter Falk", "PeterFalk", "Chris Jones", "Chris Jones", 
          "Jack Walsh", "Jack Walsh"),
 GrDate = c("10/20/2019", "6/1/2020", "8/5/2012", "1/7/2024", 
           "6/1/2020", "7/29/2018"),
 Jdate = c("10/20/2019", "11/26/2023", "8/5/2012", "1/7/2024", 
           "11/26/2023", "3/10/2019"),
  G = c(76, 76, 83, 85, 76, 76)
)

# Convert GrDate and Jdate columns to Date type
df$GrDate <- mdy(df$GrDate)
df$Jdate <- mdy(df$Jdate)
r dataframe dplyr replace
1个回答
0
投票
library(dplyr)
df |>
  mutate(
    GrDate = if_else(GrDate == '2020-06-01', first(GrDate[GrDate != '2020-06-01']), GrDate)
  )
#    Nb        Name     GrDate      Jdate  G
# 1 100  Peter Falk 2019-10-20 2019-10-20 76
# 2 100   PeterFalk 2019-10-20 2023-11-26 76
# 3 200 Chris Jones 2012-08-05 2012-08-05 83
# 4 200 Chris Jones 2024-01-07 2024-01-07 85
# 5 300  Jack Walsh 2019-10-20 2023-11-26 76
# 6 300  Jack Walsh 2018-07-29 2019-03-10 76
© www.soinside.com 2019 - 2024. All rights reserved.