Search code examples
rdplyrstrptime

Convert an entire column from character to date class in R


I am using this dataset and I am looking to convert the ArrestDate column from character in to dates so that I can work with dates for analysis.

I've first tried using mutate:

Date <- mutate(crime, ArrestDate = as.Date(ArrestDate, format= "%d.%m.%Y"))

however when I do this the entire ArrestDate column is changed to NAs.

Secondly I tried using strptime but for some reason it converts some dates fine and others to NA:

Date <-strptime(paste(crime$ArrestDate, sep=" "),"%d/%m/%Y")
crime2 <- cbind(Date, crime)

Anyone able to tell me what I am doing wrong or alternatively provide a better approach for this? Thanks.


Solution

  • Replacing the '.' with '/' works from your first example in the format:

    Date <- mutate(crime, ArrestDate = as.Date(ArrestDate, format= "%m/%d/%Y"))
    class(Date$ArrestDate)
    [1] "Date"