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

落花浮王杯 提交于 2020-12-12 05:39:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!