在R中的星期几重新排列因子水平 [英] Reorder factor levels by day of the week in R
问题描述
我在R中有以下data.frame:
>每天
DoW持续时间
1星期五14.0000000000000
2星期一21.0000000000000
3星期六12.0000000000000
4星期四28.0000000000000
5星期二12.0000000000000
6星期三91.0000000000000
7星期日20.0000000000000
我想更改因子级别的顺序,几周在(美国)星期的订单。
看起来我可以用一个缓慢,令人费解的方式做到这一点, relevel )
。但这只需要1个数字参数,并将其移动到顶部。因此, relevel(每日$ DoW,7)
,星期天移动到顶部,但其余的保持无序(这意味着我需要以相反的顺序重新排列)。 p>
可行,但必须有更好的方法,对吧?
(时间序列解决方案也可以接受。)
指定因子中的级别,然后使用订单
进行索引:
每日$ DoW<因子(每日$ DoW,levels = c(星期日,星期一,
星期二,星期三,星期四,星期五 b
$ b每日[订单(每日$ DoW)]]
I have the following data.frame in R:
> daily
DoW Duration
1 Friday 14.0000000000000
2 Monday 21.0000000000000
3 Saturday 12.0000000000000
4 Thursday 28.0000000000000
5 Tuesday 12.0000000000000
6 Wednesday 91.0000000000000
7 Sunday 20.0000000000000
I'd like to change the order of the factor levels so that the weeks are in (US) day-of-week order.
It looks like I can do this in a slow, puzzling way with relevel()
. But this only takes 1 numeric argument and moves it to the top. So, relevel(daily$DoW, 7)
, moves Sunday to the top, but the rest remain unordered (which means I need to relevel it in reverse order).
Doable, but there must be a better way, right?
(Time series solution also acceptable.)
You need to specify the levels in factor and then use order
with indexing:
daily$DoW <- factor(daily$DoW, levels= c("Sunday", "Monday",
"Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"))
daily[order(daily$DoW), ]
这篇关于在R中的星期几重新排列因子水平的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!