R:如何按名称重新排序矢量元素

时间:2018-06-17 20:25:45

标签: r vector

s <- c("West", "North", "South", "East")

我有一个包含4个元素的向量。我想对它们重新排序,因此向量包含"North", "South", "West", "East"。我知道通过索引重新排序它们的一种方法如下。

s[c(2, 3, 1, 4)]

但有没有办法按名称重新排序?类似于s["North", "South", "West," "East"]的东西(不起作用)。请注意,向量中的每个元素都是唯一的。

1 个答案:

答案 0 :(得分:3)

虽然我不确定它是否符合您的目的,但有一种方法是将您的矢量转换为ordered因子,然后转换为sort

s <- c("West", "North", "South", "East")


s <- ordered(s, c("North", "South", "West", "East"))  #Define the order in which you want it

s <- sort(s)  #Now sort vector. This could have been done as part of previous step itself

s
# [1] North South West  East 
# Levels: North < South < West < East