-1

My date data is something like this "Jun-22","Jul-22","Aug-22" Now, when I try to convert this into date, it shows NA. Then I tried to add Day, which was converted, but I want to keep the data as character. The main issue I am having is that the Date is automatically sorted alphabetically but I want to sort it by month. Now is there a way to arrange the text as a month? I don't know if this makes sense or not.

Month_Date\<-c("Jun-22","Jul-22","Aug-22","Sep-22", "Oct-22","Nov-22")

I want to keep this as it is but want to use it as "dates" and arrange it according to the month. Is there a way to do this? I don't want to have "01-06-2022".

Andre Wildberg
  • 12,344
  • 3
  • 12
  • 29
Not a pro
  • 1
  • 1
  • You could convert Month_Date to an ordered factor: `Month_Date <- factor(Month_Date, labels = Month_Date, ordered = T)`. Does that help? – jdobres Jan 27 '23 at 22:29
  • I answered this a few times over the years -- a (year. month) tuple is not and cannot be a date. You _could_ add a 'by convention' first or fifteenths or .. of the month but without a _day_ it cannot be a Date object. – Dirk Eddelbuettel Jan 27 '23 at 22:41

2 Answers2

0

You can use lubridates my to temporarily convert to date, then go back to character after sorting.

library(lubridate)

dat <- "Jun-22" "Oct-22" "Nov-22" "Sep-22" "Jul-22" "Aug-22" # unsorted

format(sort(my(dat)), "%b-%y")
[1] "Jun-22" "Jul-22" "Aug-22" "Sep-22" "Oct-22" "Nov-22"
Andre Wildberg
  • 12,344
  • 3
  • 12
  • 29
0

You can use clock's month precision year-month-day type.

library(clock)

# scrambled the OP's input
x <- c("Jun-22","Aug-22", "Oct-22","Jul-22","Nov-22","Sep-22")

x <- year_month_day_parse(x, format = "%b-%y", precision = "month")
x
#> <year_month_day<month>[6]>
#> [1] "2022-06" "2022-08" "2022-10" "2022-07" "2022-11" "2022-09"

sort(x)
#> <year_month_day<month>[6]>
#> [1] "2022-06" "2022-07" "2022-08" "2022-09" "2022-10" "2022-11"

Created on 2023-01-28 with reprex v2.0.2

Davis Vaughan
  • 2,780
  • 9
  • 19