1

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?

zx8754
  • 52,746
  • 12
  • 114
  • 209
Helena
  • 87
  • 9
  • 1
    Check out `lubridate` package. It has everything you need – dmi3kno Jun 01 '18 at 10:49
  • 1
    you can format your data into a date column with: `df$date <- as.Date( paste0(df$Day.of.the.month,df$Month,df$Year), format = '%d%B%Y')` – Chris Jun 01 '18 at 10:54
  • Related or possible duplicate https://stackoverflow.com/questions/9216138/find-the-day-of-a-week – zx8754 Jun 01 '18 at 10:59
  • @zx8754 the problem mentioned in this questions seems to be more about formatting text to a date than getting a weekday from the resulting date – Ape Jun 01 '18 at 11:03
  • @Ape Thanks, that is why didn't close the post. Just added a link to a related post. – zx8754 Jun 01 '18 at 11:20

2 Answers2

4

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")
   }
PKumar
  • 10,971
  • 6
  • 37
  • 52
1
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))
Marta
  • 27
  • 7