Reputation: 9793
s <- c("West", "North", "South", "East")
I have a vector with 4 elements. I'd like to reorder them so the vector contains "North", "South", "West", "East"
. I know one way of re-ordering them via indices as follows.
s[c(2, 3, 1, 4)]
But is there a way to re-order them by name? Something along the lines of s["North", "South", "West," "East"]
(which does not work). Note that each element in the vector is unique.
Upvotes: 1
Views: 65
Reputation: 20095
Though I'm not sure if it will fit your purpose but one option is to convert your vector to ordered
factor and then sort
it.
s <- c("West", "North", "South", "East")
s <- ordered(s, c("North", "South", "West", "East")) #Define the order in which you want it
s <- sort(s) #Now sort vector. This could have been done as part of previous step itself
s
# [1] North South West East
# Levels: North < South < West < East
Upvotes: 3