Home > Software engineering >  splitting up dates that include characters
splitting up dates that include characters

Time:07-26

I have data that looks like this:

id       visit_date
1       12FEB2021
1       01JAN2018 
2       08AUG2017
3       09MAY2013
3       10DEC2012

I want to convert "visit_date" to a date so that it looks like this:

id      new_date
1       2/12/2021
1       1/1/2018 
2       8/8/2017
3       5/9/2013
3       12/10/2012

These are 5 lines as an example, but there are close to 100 lines.

I'm new to R and I tried this, but the column "year" that's generated is blank.

df$new_date <- as.Date(df$visit_date, format = "%d_%m_%y")

Can someone help?

CodePudding user response:

You can use dmy ftom the lubridate package:

df$new_date <- strftime(lubridate::dmy(df$visit_date), "%d/%m/%Y")

df
#>   id visit_date   new_date
#> 1  1  12FEB2021 12/02/2021
#> 2  1  01JAN2018 01/01/2018
#> 3  2  08AUG2017 08/08/2017
#> 4  3  09MAY2013 09/05/2013
#> 5  3  10DEC2012 10/12/2012

Data from question in reproducible format

df <- structure(list(id = c(1L, 1L, 2L, 3L, 3L), visit_date = c("12FEB2021", 
"01JAN2018", "08AUG2017", "09MAY2013", "10DEC2012")), 
class = "data.frame", row.names = c(NA, -5L))

df
#>   id visit_date
#> 1  1  12FEB2021
#> 2  1  01JAN2018
#> 3  2  08AUG2017
#> 4  3  09MAY2013
#> 5  3  10DEC2012

Created on 2022-07-25 by the reprex package (v2.0.1)

CodePudding user response:

we could also use readr::parse_date:

library(dplyr)
library(readr)
df %>% 
  mutate(new_date = strftime(parse_date(visit_date,"%d%b%Y",locale=locale("en")), format = "%d/%m/%y"))
  id visit_date new_date
1  1  12FEB2021 12/02/21
2  1  01JAN2018 01/01/18
3  2  08AUG2017 08/08/17
4  3  09MAY2013 09/05/13
5  3  10DEC2012 10/12/12
  • Related