Morpheus
Morpheus

Reputation: 3523

Converting string to date in R returns NAs

I have a column of my dataframe as

 date
17-Feb
17-Mar
16-Dec
16-Nov
16-Sep
17-Feb

I am trying to convert it into a date column from string. I am using the following pieces of code:

 as.Date(df$Date, format="%y-%b")

and

 as.POSIXct(df$Date, format="%y-%b")

Both of them give NAs

I am getting the format from this link

The starting number is year. Sorry for the confusion.

Upvotes: 2

Views: 99

Answers (1)

Mike S
Mike S

Reputation: 312

I assume from your approach that the 17 and 16 refer to the year 2017 and 2016 respectively. You need to also specify the day of month. If you don't care about it, then set it to the 1st.

A slight modification to your code will work, by appending '-01' to the date then updating your format argument to reflect this:

df = data.frame(Date = c("17-Feb", "17-Mar", "16-Dec"))
as.Date(paste0(df$Date, "-01"), format="%y-%b-%d")

Upvotes: 3

Related Questions