TumbleWeed
TumbleWeed

Reputation: 33

How do I order a vector by attribute "names" in R but keeping the first element constant?

Say I have a vector and its name as follows:

   vct <- c(67, "apple", 88, "orange", 71)
names(vct) <- c("c1", "b2", "d66", "a65", "a11")

Now I want the first element 67 to be as is and order the rest on the order of their names. So that it appears: "67", "71", "orange", "apple", "88".

Upvotes: 2

Views: 74

Answers (2)

GKi
GKi

Reputation: 39737

You can use -1 for to exclude the first one, order the rest by it's name, add 1 and c with 1:

vct[c(1, order(names(vct)[-1])+1)]
#      c1      a11      a65       b2      d66 
#    "67"     "71" "orange"  "apple"     "88" 

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 389325

Do you mean something like this?

first <- 67
inds <- match(first, vct)
result <- vct[c(inds, setdiff(order(names(vct)), inds))]
result

#      c1      a11      a65       b2      d66 
#    "67"     "71" "orange"  "apple"     "88" 

Upvotes: 2

Related Questions