Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Custom Sort in R

I have the following data frame in R.

# Create a data frame with duplicates
df <- data.frame(
  pagePath = c(
    "/page7",
    "/page9",
    "/page3",
    "/page9",
    "/page5",
    "/page7",
    "/page4",
    "/page9",
    "/page9",
    "/page4",
    "/page5",
    "/page7"
  ),
  country = c(
    "USA",
    "Canada",
    "UK",
    "Germany",
    "France",
    "India",
    "Australia",
    "Japan",
    "Brazil",
    "India",
    "South Africa",
    "Canada"
  )
)

I want to sort data based on ordering of unique pagePath.. For example, first all rows of "/page7" should appear, then followed by all rows of "/page9", then "/page3" etc.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You may use match and unique

library(dplyr)

df %>% arrange(match(pagePath, unique(pagePath)))

#   pagePath      country
#1    /page7          USA
#2    /page7        India
#3    /page7       Canada
#4    /page9       Canada
#5    /page9      Germany
#6    /page9        Japan
#7    /page9       Brazil
#8    /page3           UK
#9    /page5       France
#10   /page5 South Africa
#11   /page4    Australia
#12   /page4        India

Or use factor

df %>% arrange(factor(pagePath, unique(pagePath)))

This can also be done in base R –

df[with(df, order(match(pagePath, unique(pagePath)))), ]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading