sadisha randinu
sadisha randinu

Reputation: 43

Clean and Format Dates in R

In my dataset, there is a column called "Date" and beginning of the all the date values there is a letter "X" . I want to convert this column to YYYY-MM-DD format. Anyone can help me please. Image of the Dataset

Upvotes: 0

Views: 906

Answers (1)

Eric
Eric

Reputation: 2849

Here is some information on how to provide a proper reproducible example.

Here is a solution using the dplyr and lubridate packages.

Data:

df <- tibble::tibble(
  Country = c("Afghanistan",
              "Algeria",
              "Andorra",
              "Angola",
              "Antigua and Barbuda",
              "Argentina",
              "Armenia",
              "Australia",
              "Austria",
              "Azerbaijan"),
  Date = c("X2020.01.22",
           "X2020.01.22",
           "X2020.01.22",
           "X2020.01.22",
           "X2020.01.22",
           "X2020.01.22",
           "X2020.01.22",
           "X2020.01.22",
           "X2020.01.22",
           "X2020.01.22"),
  Recovered = c(0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0,
                0)
)

Code:

library(lubridate)
library(dplyr)

df %>% 
  mutate(
    Date = as_date(Date, format = "X%Y.%m.%d")
  )

Output:

#> # A tibble: 10 x 3
#>    Country             Date       Recovered
#>    <chr>               <date>         <dbl>
#>  1 Afghanistan         2020-01-22         0
#>  2 Algeria             2020-01-22         0
#>  3 Andorra             2020-01-22         0
#>  4 Angola              2020-01-22         0
#>  5 Antigua and Barbuda 2020-01-22         0
#>  6 Argentina           2020-01-22         0
#>  7 Armenia             2020-01-22         0
#>  8 Australia           2020-01-22         0
#>  9 Austria             2020-01-22         0
#> 10 Azerbaijan          2020-01-22         0

Created on 2020-11-11 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions