我基本上在做
this question
不过,我正努力维持
month
列。一种迂回的方法是在单个数字上加一个前导零。我想找个办法不这么做。
当前代码:
library(dplyr)
df <- structure(list(parameters = c("temp", "temp", "temp", "temp", "temp", "temp", "temp", "temp", "temp", "temp", "temp", "temp", "temp", "temp", "temp"), month = c("2", "2", "2", "5", "5", "5", "8", "8", "8", "11", "11", "11", "annual", "annual", "annual")), class = "data.frame", row.names = c(NA, -15L))
do.call(bind_rows, by(df, df[ ,c("month", "parameters")], rbind, ""))
这个
by
函数似乎将您定义的索引强制为因子,并转换
月
一个因素表明,它使水平按这个顺序排列:
11, 2, 5, 8, annual
. 如果它是数字,它将正确地对其进行排序,但是
annual
包括,该列必须作为字符。
如果我先将它转换为一个因子,并对级别排序,我的代码将插入
NA
S.
df$month <- ordered(df$month, levels = c("2", "5", "8", "11", "annual"))
do.call(bind_rows, by(df, df[ ,c("month", "parameters")], rbind, ""))
电流输出:
parameters month
1 temp 11
2 temp 11
3 temp 11
4
5 temp 2
6 temp 2
7 temp 2
8
9 temp 5
10 temp 5
11 temp 5
12
13 temp 8
14 temp 8
15 temp 8
16
17 temp annual
18 temp annual
19 temp annual
20
期望输出:
parameters month
1 temp 2
2 temp 2
3 temp 2
4
5 temp 5
6 temp 5
7 temp 5
8
9 temp 8
10 temp 8
11 temp 8
12
13 temp 11
14 temp 11
15 temp 11
16
17 temp annual
18 temp annual
19 temp annual
20