dplyr按字符串重新排序行 [英] dplyr reordering rows by string

查看:128
本文介绍了dplyr按字符串重新排序行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据:

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?

谢谢!

推荐答案

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

这篇关于dplyr按字符串重新排序行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆