R:使用自定义顺序按名称重新排序数字向量 [英] R: Re-order numeric vector by name using custom order
问题描述
我有一个数字向量,想使用自定义顺序按名称重新排序.
I have a a numeric vector and want to re-order by name, using a custom order.
x <- sample(1:20, 5)
names(x) <- c("feb", "may", "mar", "jan", "apr")
x
feb may mar jan apr
7 10 5 13 11
如您所见,向量不是按月顺序排列的
As you can see, the vectors are not in month order
我希望使用名称通过月份顺序重新排序这个字符向量,即 jan、feb、mar、apr、may...
I wish to re-order this character vector through month order using the names, i.e. jan, feb, mar, apr, may...
这怎么可能?
注意:我追求的是一种可以用于所有名称/字符串的方法,而不是专门用于日期对象
note: I am after a method that can be used on all names/character strings, rather than specifically date objects
推荐答案
我们可以将'x'的names
转换为factor
并设置levels
到小写的 month.abb
,应用 order
并按该顺序获取 'x'.
We can convert the names
of 'x' to factor
and settting the levels
to the month.abb
in lowercase, apply the order
and get the 'x' in that order.
x[order(factor(names(x), levels=tolower(month.abb)))]
jan feb mar apr may
13 7 5 11 10
转换为 factor
并指定 levels
可以按自定义顺序应用于任何字符向量,否则,默认情况下,排序基于字母顺序,即
The conversion to factor
with levels
specified can be applied to any character vector in a custom order, otherwise, by default, the ordering is based on alphabetical order i.e.
x[order(names(x))]
假设,如果希望顺序为jan"、mar"、apr"、may"、feb",请将其用作 factor 中的
levels
调用
Suppose, if want the order to be say, 'jan', 'mar', 'apr', 'may', 'feb', use that as levels
in the factor
call
x[order(factor(names(x), levels = c('jan', 'mar', 'apr', 'may', 'feb')))]
<小时>
因为 OP 在评论中以自定义顺序发布了另一个向量
As the OP posted another vector in a custom order in the comments
x1 <- c(icecream = 3, jelly = 4, fruit = 5)
x1[order(factor(names(x1), levels = c("jelly", "fruit", "icecream")))]
# jelly fruit icecream
# 4 5 3
这篇关于R:使用自定义顺序按名称重新排序数字向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!