Closed. This question is
I want to convert that column to a date, but I'm not sure how to because of the abbreviated month in the middle of the string. I've tried mutating a number of ways, but can't seem to get it to work.
Ultimately, my goal is to use diff_time() to show how many days from January 1st 2003 each entry is. For instance, January 3rd, 2003 would be displayed as 3, and January 5th, 2004 would be displayed as 370 and so on and so forth. Here is what I'm working with at the moment:
data$contact_date1 <- as.Date(data$contact_date1, format="%d-%m-%y")
data$contact_date1 <- difftime(
as.POSIXct("2003-01-01 12:00:00"),
data$contact_date1,
unit = "days")
Any help would be very appreciated! Thanks so much.
CodePudding user response:
As stated in the comments, you should use %b
to decode your dates.
Have a look at the ?strptime
help page for this.
first.date <- as.POSIXct("2003-01-01 12:00:00")
weird.dates <- c("17NOV03","06May02")
?strptime
times <- as.Date(weird.dates, format = "%d%b%y")
difftime(time1 = first.date, time2 = times)
Created on 2021-09-19 by the reprex package (v2.0.1)
CodePudding user response:
Use the package lubridate
; its function dmy
converts your data format into the yyyy-mm-dd
format:
library(lubridate)
round(difftime(dmy(data$contact_date1),"2003-01-01", units = "days"), 0)
Time differences in days
[1] 9 45
To add the days to the dataframe:
data$days <- round(difftime(dmy(data$contact_date1),"2003-01-01", units = "days"), 0)
Toy data:
data <- data.frame(
contact_date1 = c("10JAN2003", "15FEB2003")
)