0

I have a data frame like;

dataframe <- data.frame(country=c("Japan","Korea","China","Japan","Korea","China","Japan","Korea","China"),
           count=c(4,5,6,1,2,3,0,2,3))

Now I want to sort by the country like;

dataframe <- data.frame(country=c("Japan","Japan","Japan","Korea","Korea","Korea","China","China","China"),
                        count=c(4,1,0,5,2,2,6,3,3))

I tried grouped_by function, but it doesn't work. Please tell me how to do.

zx8754
  • 42,109
  • 10
  • 93
  • 154
tantan
  • 57
  • 5
  • @RonakShah Nice base R option, however, it is in a different order than OP stated in the expected output. I couldn't come up with a base R solution myself (only `dplyr`) but am interested if there is one ;) – user213544 Feb 05 '20 at 08:23
  • 2
    you can use `match` in the same way : `dataframe[with(dataframe, order(match(country, c("Japan", "Korea", "China")), -count)), ]` – Ronak Shah Feb 05 '20 at 08:34

1 Answers1

1

You can use the arrange function of the dplyr package:

library(tidyverse)

dataframe <- dataframe %>% 
      arrange(match(country, c("Japan", "Korea", "China")))
user213544
  • 1,560
  • 1
  • 8
  • 28