'inconsistent date format. Fixing it using is.na() and creating a new column with a unified format

enter image description here

heres what happens after I do

bdata$Period <- as.Date(cdata$Period,"%Y-%m-%d")
bdata

enter image description here

So how do I convert the dates that are still in character format using is.na, to create a new column with all the dates like %Y-%m-%d?



Solution 1:[1]

You could try this ...

library(tidyverse)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union

tibble(date = c("2022-01-01", "02/01/2022")) |>
  mutate(clean_date = if_else(str_detect(date, "/") == TRUE, dmy(date), ymd(date)))
#> Warning: 1 failed to parse.

#> Warning: 1 failed to parse.
#> # A tibble: 2 × 2
#>   date       clean_date
#>   <chr>      <date>    
#> 1 2022-01-01 2022-01-01
#> 2 02/01/2022 2022-01-02

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Carl