smarter way relevel column containing alphanumerical date in R

Viewed 42

so for data below, I am looking for a neat way to help R understand Dec 2009 should come before Jan 2022 and so on. I can achieve this by releving the factor column maually. but is there another way in case I have a broad range of date.

library(dplyr)
library(ggplot2)
df <- data.frame(date = c("Jan-2010", "Feb-2010", "Mar-2010", "Apr-2010" ,"Dec-2009"),
                 value = c(2,1,4,3, 2))
df %>%

  ggplot() +
  geom_line(aes(x=date,
                y=value),
            group=1)

enter image description here

2 Answers

Lubridate is great for these types of issues. We can use lubridate's ym function:

library(lubridate)
df <- data.frame(date = c("Jan-2010", "Feb-2010",
 "Mar-2010", "Apr-2010" ,"Dec-2009"), value = c(2,1,4,3, 2))
df$date <- lubridate::my(df$date)
df %>% ggplot() +
  geom_line(aes(x=date,
                y=value),
            group=1)+
    scale_x_date(date_labels="%b %Y")

enter image description here

Try the code below:

df %>%
  mutate(date = zoo::as.yearmon(date, "%b-%Y")) %>%
  ggplot() +
  geom_line(aes(x=date,
                y=value),
            group=1) +
  scale_x_continuous(labels = df$date)

enter image description here

Related