2

I am trying to sort my dataframe alphabetically by state (it is technically out of order as of now), and then try sorting the IncomeID column by 1-6 for every six rows. It should follow the pattern 1,2,3,4,5,6,1,2,3,4,5,6 and so on for the entire dataset. Take note of rows 7-12, whose order is incorrect. I know how to sort the states alphabetically, but I am unsure of the second part, or if it is even a possibility. I have included a picture of the relevant columns.

Any help is greatly appreciated.

Snip of df

autechre
  • 45
  • 2
  • 2
    Did you read [How to sort a dataframe by multiple column(s)](https://stackoverflow.com/questions/1296646/how-to-sort-a-dataframe-by-multiple-columns) ? – markus Dec 07 '20 at 21:14
  • 1
    @markus I think the question is more than that – akrun Dec 07 '20 at 21:17
  • @markus - Yes, however, my situation was a bit different than that one unfortunately – autechre Dec 07 '20 at 21:21

1 Answers1

1

Here is an option with arrange, where we create a grouping index with gl for every 6 rows, and use that in the arrange along with 'IncomeID'

library(dplyr)
df1 %>%
     arrange(LocationDesc, as.integer(gl(n(), 6, n())), IncomeID)
akrun
  • 674,427
  • 24
  • 381
  • 486