Lubridate as_date

I imported a dataset using read_csv. When I check the class of my date column, it says 'character'.
So i wanted to change it using as_date(data$column) but it change all the dates to NA.

What am I doing wrong?

It's hard to know for sure without a REPRoducible EXample (reprex) but maybe your problem is with your date format, the default is %Y-%m-%d if your date column has a different format, then you need to specify it with the format parameter e.g.

as_date(data$column, format = '%m-%d-%Y') 

If you need more specific help, please provide a reprex. A reprex makes it much easier for others to understand your issue and figure out how to help.

If you've never heard of a reprex before, you might want to start by reading this FAQ:

1 Like

Here's the sample dataset:

A, 12/3/1990
B, 1/1/2000
C, 11/13/2001
D, 2/2/2002
E, 12/23/1999

Here's the code I am using:

data <- read_csv("file.csv)
x <- data %>%
as_date(col2)

The error I get is:
do not know how to convert 'x' to class β€œDate”

Here's ready tibble and code is used:

f <- tribble(~a, ~date,
               "BVH", "1/1/2019",
               "HBYU", "12/12/1990",
               "CYC", "1/11/1999",
               "AC", "12/10/2000")
summary(f)
g <- f %>%
  as_date(date)

You could use lubridate::dmy():

2 Likes

Tried it already. Doesn't work

you need to use it in combination with mutate

library(dplyr)
library(lubridate)

f <- tribble(~a, ~date,
             "BVH", "1/1/2019",
             "HBYU", "12/12/1990",
             "CYC", "1/11/1999",
             "AC", "12/10/2000")

g <- f %>%
    mutate(date = mdy(date))
g
#> # A tibble: 4 x 2
#>   a     date      
#>   <chr> <date>    
#> 1 BVH   2019-01-01
#> 2 HBYU  1990-12-12
#> 3 CYC   1999-01-11
#> 4 AC    2000-12-10

Created on 2019-03-20 by the reprex package (v0.2.1)

5 Likes

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.