Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an entire column from character to date class in R [duplicate]

Tags:

r

dplyr

strptime

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.

like image 350
ka4c Avatar asked Oct 15 '25 04:10

ka4c


2 Answers

The lubridate package offers some very useful functions to transform strings into dates. In this case you can use mdy() since the format is '%m/%d/%Y' (as can be derived from the first record which is '12/31/2019').

library(dplyr)
library(lubridate)

crime %>% 
  mutate(ArrestDate = mdy(ArrestDate))
like image 158
pieterbons Avatar answered Oct 16 '25 17:10

pieterbons


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"
like image 37
bs93 Avatar answered Oct 16 '25 17:10

bs93