1

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.

  • 1
    seems like its `month/day/year` format. Maybe you just need to modify your code a bit – Frank Zhang Apr 21 '20 at 12:28
  • Hi @FrankZhang thanks that worked for method 2 as the month and date were the wrong way around, however the mutate function did the same thing as before after I corrected the date format. Any idea what's wrong with that particular code? – shaneconn860 Apr 21 '20 at 12:33
  • if you pass the same format `%m/%d/%Y` to your first line of code. It should also work. – Frank Zhang Apr 21 '20 at 12:41

2 Answers2

2

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))
pieterbons
  • 1,157
  • 7
  • 10
1

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"
bs93
  • 1,061
  • 4
  • 9