问题
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".
回答1:
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"
回答2:
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"
来源:https://stackoverflow.com/questions/64889260/how-do-i-order-a-vector-by-attribute-names-in-r-but-keeping-the-first-element