使用自定义顺序重新排列行 [英] Reorder rows using custom order

查看:88
本文介绍了使用自定义顺序重新排列行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定数据:

library(data.table)
DT = data.table(category=LETTERS[1:3], b=1:3)
DT
#    category b
# 1:        A 1
# 2:        B 2
# 3:        C 3

使用 dplyr ,如何重新排列在类别中获得具体订单 c(C,A,B)

Using dplyr, how to rearrange rows to get specific order c("C", "A", "B") in category?

#    category b
# 1:        C 3
# 2:        A 1
# 3:        B 2


推荐答案

首先,创建一个带有所需字母的向量订购。然后匹配 *带有要排序的变量的向量。 匹配返回(第一个)匹配的索引,可以插入切片

First, create a vector with the letters in the desired order. Then match* the vector with the variable to be sorted. match returns indices of (first) matches, which can be plugged into slice:

library(dplyr)

# create a vector with letters in the desired order
x <- c("C", "A", "B")

DT %>%
  slice(match(x, category))
#   category b
# 1        C 3
# 2        A 1
# 3        B 2

另一种方法是将类别转换为因子,将级别设置为所需的顺序,然后使用安排

Another way would be to convert "category" to a factor, set levels to the desired order, and use arrange:

DT %>%
  mutate(category =  factor(category, levels = x)) %>%
  arrange(category)    
#   category b
# 1        C 3
# 2        A 1
# 3        B 2

* 匹配方法灵感来自t他的回答

*The match method is inspired by this answer.

这篇关于使用自定义顺序重新排列行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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