Reputation: 87
This could seem a repetition but I haven't found this exact question's answer yet. I have this dataframe:
Day.of.the.month Month Year Items Amount.in.euros
1 1 January 2005 Nothing 0.00
2 2 February 2008 Food 7.78
3 3 April 2009 Nothing 0.00
4 4 January 2016 Bus 2.00
I want to create a column named "day.of.the.week" including, of course, "saturday", "sunday" and so on. If the date was formatted as '2012/02/02' I would not have probs, but this way I don't know whether there is a way nor a workaround to solve the issue.
Any hint?
Upvotes: 1
Views: 116
Reputation: 27
Day.of.the.month<-as.numeric(c(1,2,3,4))
Month<-as.character(c("January","February","April","January"))
Year<-as.numeric(c(2005,2008,2009,2016))
Items<-as.character(c("Nothing","Food","Nothing","Bus"))
Amount.in.euros<-as.numeric(c(0.00,7.78,0.0,2.0))
complete.date<-paste(Year,Month,Day.of.the.month)
strptime(complete.date, "%Y %B %d")
example1.data <-
data.frame(Day.of.the.month,Month,Year,Items,Amount.in.euros,complete.date)
example1.data$weekday <- weekdays(as.Date(example1.data$complete.date))
Upvotes: 1
Reputation: 11128
Do you want this?
options(stringsAsFactors = F)
df <- data.frame( x = c(1, 2, 3, 4) ,y = c("January", "February","April", "January"), z = c(2005, 2008, 2009, 2016))
weekdays(as.Date(paste0(df$x, df$y, df$z),"%d%B%Y")) # %d for date, %B for month in complete and %Y for year complete
This is just a side note
Note: Since someone commented that this solution is being locale dependent. So if that is the case you can always do "Sys.setlocale("LC_TIME", "C")
" to change your locale settings also, use Sys.getlocale()
to get your locale settings.
If someone interested in making this permanent while starting the R session everytime:
You can also write below script on your .RProfile
file (which is usually located at your home directory , in windows it is mostly found at Documents folder):
.First <- function() {
Sys.setlocale("LC_TIME", "C")
}
Upvotes: 4