Partial dates in R

I have partial dates from three different variables , (imputations not required )
From.year (having year as "2022" and some blank values)
From.month(having month as "12" and some single digit values "2")
From.day(having day as "27", and some single digit values "5")

I need to concatenate all three From.year-From.month.From.day

if From.year and missing (From.month) then New_date = 2022
if From.year and not missing (From.month) then New_date = 2022-12
if From.year and not missing (From.month) , for single value in month 2 then New_date = 2022-02
if From.year and not missing (From.month) and not missing (day), then New_date = 2022-02-27
if From.year and not missing (From.month) and not missing (day), for single value in day 5 then New_date = 2022-02-05

Does this do what you want?

library(stringr)

DF <- data.frame(from.year = c(2022, 2022, 2022, 2022, 2022),
                 from.month = c(NA, 12,5,12,1),
                 from.day = c(NA, NA, 5,27,5))
DF
#>   from.year from.month from.day
#> 1      2022         NA       NA
#> 2      2022         12       NA
#> 3      2022          5        5
#> 4      2022         12       27
#> 5      2022          1        5
DF$new.date <-  paste(DF$from.year, 
                      formatC(DF$from.month, width = 2, flag = "0"),
                      formatC(DF$from.day, width = 2, flag = "0"), 
                      sep = "-")
DF$new.date <- str_remove_all(DF$new.date, "-NA")
DF
#>   from.year from.month from.day   new.date
#> 1      2022         NA       NA       2022
#> 2      2022         12       NA    2022-12
#> 3      2022          5        5 2022-05-05
#> 4      2022         12       27 2022-12-27
#> 5      2022          1        5 2022-01-05

Created on 2023-10-13 with reprex v2.0.2

1 Like

Thank you so much this is great, simple to understand

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.