Search code examples
rdatediffdate-difference

R function for finding difference of dates with exceptions?


I was wondering if there was a function for finding the difference between and issue date and a maturity date, but with 2 maturity date. For example, I want to prioritize the dates in maturity date source 1 and subtract it from the issue date to find the difference. Then, if my dataset is missing dates from maturity date source 1, such as in lines 5 & 6, I want to use dates from maturity date source 2 to fill in the rest. I have tried the code below, but am unsure how to incorporate the data from maturity date source 2 without changing everything else. I have attached a picture for reference. Thank you in advance.

    df$Maturity_Date_source_1 <- as.Date(c(df$Maturity_Date_source_1))
df$Issue_Date <- as.Date(c(df$Issue_Date))
df$difference <- (df$Maturity_Date_source_1 - df$Issue_Date) / 365.25
df$difference <- as.numeric(c(df$difference))

enter image description here


Solution

  • An option would be to coalesce the columns and then do the difference

    library(dplyr)
    df %>%
       mutate(difference = as.numeric((coalesce(Maturity_Date_source_1, 
                        Maturity_Date_source_2) - Issue_Date)/365.25))