R根据条件在日期列中增加年份

时间:2019-12-12 21:52:23

标签: r dplyr lubridate

我想根据条件在“日期”列中增加年份-如果StartDate晚于EndDate,则在EndDate中增加年份,例如:

数据:

input_df <- structure(list(C1 = c("A", "C", "E", "G", "I"), C2 = c("B", "D", "F", "H", "J"), 
                           StartDate = c("12/23/2019", "12/24/2019", "12/28/2019", "01/01/2019", "05/15/2019"), EndDate = c("01/07/2019", "12/25/2019", "12/31/2019", "04/11/2019", "05/18/2019")), class = "data.frame", row.names = c(NA, -5L))

input_df:
  C1 C2  StartDate    EndDate
1  A  B 12/23/2019 01/07/2019
2  C  D 12/24/2019 12/30/2019
3  E  F 12/28/2019 12/30/2019
4  G  H 01/01/2019 04/18/2019
5  I  J 05/15/2019 05/25/2019

预期输出: input_df:

  C1 C2  StartDate    EndDate
1  A  B 12/23/2019 01/07/2020
2  C  D 12/24/2019 12/25/2019
3  E  F 12/28/2019 12/31/2019
4  G  H 01/01/2019 04/11/2019
5  I  J 05/15/2019 05/18/2019

我试图做到以下几点:

library(lubridate)
input_df$EndDate[input_df$EndDate < input_df$StartDate] <- mdy(input_df$EndDate) + years(1)

但是我收到的输出是:

  C1 C2  StartDate    EndDate
1  A  B 12/23/2019      18268
2  C  D 12/24/2019 12/25/2019
3  E  F 12/28/2019 12/31/2019
4  G  H 01/01/2019 04/11/2019
5  I  J 05/15/2019 05/18/2019

警告:“要替换的项目数不是替换长度的倍数”

3 个答案:

答案 0 :(得分:3)

我认为您遇到了错误,因为您只对左侧进行了分组。另外,您可能想为StartDateEndDate使用相同的类。试试这个:

input_df$StartDate <- mdy(input_df$StartDate)
input_df$EndDate <- mdy(input_df$EndDate)

input_df$EndDate[input_df$EndDate < input_df$StartDate] <- 
  input_df$EndDate[input_df$EndDate < input_df$StartDate] + years(1)

input_df

答案 1 :(得分:1)

使用tidyverse软件包:

input_df %>% mutate(StartDate = as.Date(StartDate, format = "%m/%d/%Y"), 
EndDate = as.Date(EndDate, format = "%m/%d/%Y"), 
EndDate_N = if_else(StartDate >= EndDate, EndDate + years(1), EndDate))

答案 2 :(得分:0)

我们也可以使用基数R

#Convert Start and End date to `POSIXlt` format
input_df[c('StartDate','EndDate')] <- lapply(input_df[c('StartDate','EndDate')], 
                                       as.POSIXlt, format = "%m/%d/%Y")
#Get the row index where StartDate > EndDate
inds <- input_df$StartDate > input_df$EndDate
#Increment the year for those indexes
input_df$EndDate[inds]$year <- input_df$EndDate[inds]$year + 1

input_df
#  C1 C2  StartDate    EndDate
#1  A  B 2019-12-23 2020-01-07
#2  C  D 2019-12-24 2019-12-25
#3  E  F 2019-12-28 2019-12-31
#4  G  H 2019-01-01 2019-04-11
#5  I  J 2019-05-15 2019-05-18