Mrmoleje
Mrmoleje

Reputation: 493

dplyr reordering rows by string

I have the following data:

library(tidyverse)


d1 <- data_frame(Nat = c("UK", "UK", "UK", "NONUK", "NONUK", "NONUK"),
 Type = c("a", "b", "c", "a", "b", "c"))

I would like to rearrange the rows so the dataframe looks like this:

d2 <- data_frame(
 Nat = c("UK", "UK", "UK", "NONUK", "NONUK", "NONUK"),
 Type = c("b", "c", "a", "b", "c", "a"))

So the UK and Non UK grouping remains, but the 'Type' rows have shifted. This questions is quite like this one: Reorder rows conditional on a string variable

However the answer above is dependent on the rows you are reordering being in alphabetical order (excluding London). Is there a way to reorder a string value more specifically where you select order of the rows yourself, rather than relying on it being alphabetical? Is there a way to do this using dplyr?

Thanks!

Upvotes: 0

Views: 2048

Answers (2)

s__
s__

Reputation: 9485

What about explicit the levels in a dplyr chain, to choose your order:

library(dplyr)
d1 %>%
arrange(factor(.$Nat, levels = c("UK", "NONUK")), factor(.$Type, levels = c("c", "b","a")))

# A tibble: 6 x 2
  Nat   Type 
  <chr> <chr>
1 UK    c    
2 UK    b    
3 UK    a    
4 NONUK c    
5 NONUK b    
6 NONUK a

Another example:

d1 %>%
arrange(factor(.$Nat, levels = c("UK", "NONUK")), factor(.$Type, levels = c("b", "c","a")))
# A tibble: 6 x 2
  Nat   Type 
  <chr> <chr>
1 UK    b    
2 UK    c    
3 UK    a    
4 NONUK b    
5 NONUK c    
6 NONUK a 

Upvotes: 2

markus
markus

Reputation: 26343

You could use match

string_order <- c("b", "c", "a")
d1 %>% 
  group_by(Nat) %>% 
  mutate(Type = Type[match(string_order, Type)]) %>%
  ungroup()
#  A tibble: 6 x 2
#  Nat   Type 
#  <chr> <chr>
#1 UK    b    
#2 UK    c    
#3 UK    a    
#4 NONUK b    
#5 NONUK c    
#6 NONUK a 

Upvotes: 2

Related Questions