dplyr按字符串重新排序行

时间:2018-10-01 11:58:48

标签: r dplyr

我有以下数据:

library(tidyverse)


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

我想重新排列行,以便数据框看起来像这样:

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

因此,保留了UK和Non UK分组,但“类型”行已转移。这个问题很像这样:Reorder rows conditional on a string variable

但是,以上答案取决于您要重新排序的行的字母顺序(伦敦除外)。有没有一种方法可以更具体地对字符串值进行重新排序,您可以自己选择行的顺序,而不是依赖于字母顺序?有没有办法使用dplyr做到这一点?

谢谢!

2 个答案:

答案 0 :(得分:2)

您可以使用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 

答案 1 :(得分:2)

如何显式显示dplyr链中的级别以选择订单:

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

另一个例子:

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