I'm basically doing what is described in this question, however I'm trying to maintain the original order of the month
column. A roundabout way would be to add a leading zero to the single digit numbers. I'm trying to find a way without doing that.
Current code:
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, ""))
The by
function looks like it coerces your defined indices to factors, and converting month
to a factor reveals that it makes the levels in that order: 11, 2, 5, 8, annual
. If it were numeric, it would order them correctly, but with annual
included, that column must be as a character.
If I convert it to a factor first, and order the levels, my code will insert 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, ""))
Current output:
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
Desired output:
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