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

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

问题描述

给定数据:

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,如何重新排列行以获得category中的特定顺序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

推荐答案

首先,按照所需的顺序创建一个包含字母的向量.然后将向量与要排序的变量match*.match 返回(第一个)匹配项的索引,可以插入到 slice 中:

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

另一种方法是将类别"转换为 factor,将 levels 设置为所需的顺序,然后使用 arrange:

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

*match 方法的灵感来自于 这个答案.

*The match method is inspired by this answer.

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

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