how to arrange rows in data frame

How to order the rows by year and month, so the year 2022 month 10 and 11 are the last 2 rows? Thanks,

test <- data.frame(
stringsAsFactors = FALSE,
datec = c("03/21","04/21","08/21",
"10/22","11/22","05/22","07/22","08/22","09/22"),
year = c("2021","2021","2021","2022",
"2022","2022","2022","2022","2022"),
mon = c("3", "4", "8", "10", "11", "5", "7", "8", "9"),
row = c(1,2,3,4,5,6,7,8,9)
)

df <- test %>% arrange(year,mon)

Your are sorting characters !
Convert the character strings to numeric and the order will be as you expect:

df <- test %>% 
  mutate(year=as.integer(year),
         mon =as.integer(mon) ) %>%
  arrange(year,mon)
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.