Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tidyverse Parse Date String

I have a "date" column in a data frame that has a space after the date. I want to FIND the space, then go LEFT to that position minus 1 spot, and convert that string into a date. This is a representative example:

library(tidyverse)
library(lubridate)

my_sales <- c(10, 15, 20, 15)
my_dates <- c("12/30/02 0:00", "1/4/03 0:00", "1/11/03 0:00", "1/19/03 0:00")
df <- data.frame(my_sales, my_dates)
df$my_dates <- as.character(df$my_dates)

df$my_dates_temp1 <- str_sub(df$my_dates, 1, str_locate(df$my_dates, ' ')[, 1]-1)
head(df)

>   my_sales      my_dates my_dates_temp1
> 1       10 12/30/02 0:00       12/30/02
> 2       15   1/4/03 0:00         1/4/03
> 3       20  1/11/03 0:00        1/11/03
> 4       15  1/19/03 0:00        1/19/03

My issue is when I try to convert my_dates_temp1 to a date.

Base R

as.Date(df$my_dates_temp1)
> Error in charToDate(x) : 
>   character string is not in a standard unambiguous format

lubridate

lubridate::as_date(df$my_dates_temp1)
> [1] NA NA NA NA
> Warning message:
> All formats failed to parse. No formats found. 

How is this not in a format that can be converted to a date and how can I convert it?

like image 702
Frank B. Avatar asked Jul 14 '26 08:07

Frank B.


1 Answers

We need the format as it is not in the default format of "YYYY-MM-DD"

as.Date(df$my_dates_temp1, "%m/%d/%y")
#[1] "2002-12-30" "2003-01-04" "2003-01-11" "2003-01-19"

or use

lubridate::mdy(df$my_dates_temp1)
#[1] "2002-12-30" "2003-01-04" "2003-01-11" "2003-01-19"
like image 177
akrun Avatar answered Jul 16 '26 00:07

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!