Reputation: 161
I tried to reorder my columns but unable to figure out how to do it for a certain order in my column. For eg. I have the following data.frame
df <- data.frame(name=c("a","a","a","b","b","c","c","c","c"), time=c("screen","third","second","first","second","fourth","third","first","screen"), first_values=c("0.11", "0.23", "0.03", "0.4", "0.10", "0.25", "0.87","0.11","0.21"), second_values=c("0.05", "0.32", "0.63", "0.67", "0.10", "0.25", "0.87","0.11","0.91"))
target.time <- c("zeros", "screen", "first", "second", "third", "fourth")
So my goal is to order by name and by time; but time needs to be in the order described by target.time.
I can achieve multiple column ordering by doing the following;
df_reorder <- df[order(df$name, df$time), ]
But I don't know how to order time with target.time order while df$name remains unique for the pertinent rows.
Upvotes: 1
Views: 69
Reputation: 38520
One common method is to reorder the factor levels of df$time
and then use order
.
# reassign factor levels according to target.time
df$time <- factor(df$time, levels=target.time)
# order data.frame
df[order(df$name, df$time),]
name time first_values second_values
1 a screen 0.11 0.05
3 a second 0.03 0.63
2 a third 0.23 0.32
4 b first 0.4 0.67
5 b second 0.10 0.10
9 c screen 0.21 0.91
8 c first 0.11 0.11
7 c third 0.87 0.87
6 c fourth 0.25 0.25
Upvotes: 4