Sorting a frequency matrix by weekday sequence in R

Question

I am doing some exploratory stuff on a data set that includes certain transactions.

Every row represents a transaction with a specific date. I want to produce a frequency matrix of transactions for the different weekdays.

table(weekdays(x$date))

This is working but the weekdays are in alphabetical order (e.g. Mo, Fr, Sa, Tu..) instead of logical order (Mo, Tu, We..).

Anybody knows how to fix that easily? Or do I have to factorize the result?

Best wishes, Marcus


Show source
| sorting   | R   | matrix   | frequency   2017-01-06 16:01 1 Answers

Answers ( 1 )

  1. 2017-01-06 16:01

    Use a factor:

    # oldlocale <- Sys.getlocale("LC_TIME")
    # Sys.setlocale("LC_TIME", "english")
    table(factor(
      weekdays(Sys.Date()+0:7), 
      levels=c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
    ))
       # Monday   Tuesday Wednesday  Thursday    Friday  Saturday    Sunday 
       #      1         1         1         1         2         1         1 
    # Sys.setlocale("LC_TIME", oldlocale)
    
◀ Go back