Jose Rolando Josue
Jose Rolando Josue

Reputation: 138

R Lubridate is ordering months and weekdays alphabetically by default

I'm using Lubridate in R Studio and when I use group by (with dplyr) to group by months or weekdays it sorts it automatically in alphabetical order. How can I change this to date order?

Here is the code:

df %>% group_by(months(DateColumn)) %>% summarise(Freq=n())

DateColumn has te following structure:

enter image description here

When I view the result this is the order. (Same for plots)

enter image description here

Upvotes: 0

Views: 1473

Answers (3)

Dan
Dan

Reputation: 286

You aren't using lubridate here at all. If you were, then it would work as you wanted. months is a base R function. The function you want is month, with label=TRUE.

df |> group_by(month(DateColumn,label=TRUE)) |> summarise(Freq=n())

Which gives the below output (I don't have your exact data, so I used my own):

  `month(timestamp, label = TRUE)`  Freq
  <ord>                            <int>
1 Jan                                 10
2 Mar                                 25
3 Apr                                  6
4 Aug                                 15
5 Sep                                 12
6 Oct                                 10
7 Nov                                  9

Upvotes: 0

NelsonGon
NelsonGon

Reputation: 13319

Using data from @akrun's answer. Here is an alternative:

 df <- data.frame(DateColumn = seq(as.POSIXct("2015-05-10"), 
                                  length.out = 30, by = '1 month'))
df %>% 
  mutate(Date=month(DateColumn,label=T),ID=row_number()) %>%
  group_by(Date) %>% 
  arrange(Date) %>% 
  select(-DateColumn)

Upvotes: 1

akrun
akrun

Reputation: 887531

After the summarise step, we can arrange the rows by matching with the inbuilt month.name (months in the correct order), and then convert the 'Months' to a factor with levels specified (so that it can be used later in ggplot to order in the same order as the levels)

library(tidyverse)
df %>%
  group_by(Months = months(DateColumn)) %>% 
  summarise(n = n()) %>%
  arrange(match(month.name, Months)) %>%
  mutate(Months = factor(Months, levels = Months))

data

df <- data.frame(DateColumn = seq(as.POSIXct("2015-05-10"), 
     length.out = 30, by = '1 month'))

Upvotes: 1

Related Questions