orangeman51
orangeman51

Reputation: 541

specifying as.Date format returns NA in R

I have the following DF:

date <- c("2017-10-11","2018-04-02","2017-05-03")
df <- data.frame(date)

The following code fails to format it as a date, instead returning NAs:

df$date <- as.Date(df$date,format='%Y/%m/%d')

The following code successfully formats it as a date:

df$date <- as.Date(df$date)

I've specified the as.Date format (as in the first as.Date code) in other projects and it has worked for me before. There are numerous responses to similar questions about as.Date returning NAs, but I can't find any that explain why my first as.Date code doesn't work in this situation, but my second one does. I don't need to specify the format for my purposes, but I would like to understand why the first line of code does not work.

Upvotes: 3

Views: 5583

Answers (1)

MKR
MKR

Reputation: 20085

The default value for format argument of as.Date function is "%Y-%m-%d" which is matching with the format of date column of df.

Hence, df$date <- as.Date(df$date) works perfectly.

The R-Studio help describes format argument as:

format

A character string. If not specified, it will try "%Y-%m-%d" then "%Y/%m/%d" on the first non-NA element, and give an error if neither works. Otherwise, the processing is via strptime

But, df$date <- as.Date(df$date,format='%Y/%m/%d') will not work. The reason is that separator / mentioned as part of format is not present in the data column.

Upvotes: 2

Related Questions