Reputation: 1017
I am adding a day-name column to a data frame that has a date column. Something like this:
date<-c ("01/09/2014", "24/08/2014", "28/08/2014")
id<-(1:3)
df<-data.frame(date,id)
df$day<-weekdays(as.Date(df$date))
However, the resulting column does not match the actual days. In the above example, for instance, September 1 is Thursday, while in reality it was a Monday. Thanks for your help.
Upvotes: 1
Views: 43
Reputation: 521289
You need to specify the formatting when you call as.Date()
. Try this code:
df$day <- weekdays(as.Date(df$date, format = "%d/%m/%Y"))
Be careful with the last formatting parameter. If you use lowercase y, %y
, you will get the wrong answer.
> df
date id day
1 01/09/2014 1 Monday
2 24/08/2014 2 Sunday
3 28/08/2014 3 Thursday
Upvotes: 1