Jake
Jake

Reputation: 91

Parsing date in R

I want to parse a date in the format "01012020" in R, but every example I have seen is using something like:

parse_date("01/02/2010", "%d/%m/%Y")

Perhaps I'm not understanding this correctly? But it looks as if using this I would need the date format to already be using separators (-,/).

This is what I've tried:

parse_date("01012020", "%d/%m/%Y")

And I get this error:

Error in parse_vector(x, col_date(format), na = na, locale = locale, trim_ws = trim_ws) : is.character(x) is not TRUE

I am also curious if this will loop over an entire dataframe? the one I'm using could get quite tedious if not...

Upvotes: 1

Views: 1105

Answers (1)

Gregor Thomas
Gregor Thomas

Reputation: 145755

If your date format doesn't have separators, then don't include separators in the format string.

as.Date("01012020", "%d%m%Y")
# [1] "2020-01-01"

This is vectorized, so you can use it on a whole column at once: my_data$date_column <- as.Date(my_data$date_column, "%d%m%Y"). For multiple columns, you might do something like this:

date_columns = c("date_col_1", "start_date", "birth_date")
my_data[date_columns] = lapply(my_data[date_columns], as.Date, format = "%d%m%Y")

Upvotes: 4

Related Questions