Replace certain digits representing year in date

Viewed 46

I am using a dbplyr package to tidy data from database table. I have a column with dates as below:

Date      
   <date>    
 1 6202-06-21
 2 6015-08-05
 3 5012-05-18
 4 3201-10-13
 5 3021-03-08
 6 3018-03-19
 7 3018-01-31
 8 3015-03-30
 9 3014-03-03
10 3013-05-31
# ... with more rows

The years are apparently wrong but only the first digit or two (depending on case) need to be replaced. How to accomplish it please? I was trying to use the str_sub() in following way:

mutate(
    Date = str_sub((Date), 1, 2) <- "20"
) 

I am getting this error message:

Error: nanodbc/nanodbc.cpp:1655: 42883: ERROR: function substr(date, integer, integer) does not exist; Error while preparing parameters RROR: function substr(date, integer, integer) does not exist;

1 Answers

A possible solution:

library(tidyverse)

df <- data.frame(
  Date = c("6202-06-21","6015-08-05",
           "5012-05-18","3201-10-13","3021-03-08","3018-03-19",
           "3018-01-31","3015-03-30","3014-03-03","3013-05-31")
)

df %>% 
  mutate(Date = str_replace(Date, "^\\d{2}", "20"))

#>          Date
#> 1  2002-06-21
#> 2  2015-08-05
#> 3  2012-05-18
#> 4  2001-10-13
#> 5  2021-03-08
#> 6  2018-03-19
#> 7  2018-01-31
#> 8  2015-03-30
#> 9  2014-03-03
#> 10 2013-05-31
Related