【问题标题】:How can I order a vector by the order of its attributes in R?如何按照 R 中的属性顺序对向量进行排序?
【发布时间】:2021-03-01 06:48:55
【问题描述】:

假设我有一个向量,其名称如下:

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

当我跑步时:

sort(vct)

向量是根据元素排序的;相反,我希望它根据其名称进行排序,以便向量排序为“71”、“橙色”、“苹果”、“67”、“88”。

提前致谢!

【问题讨论】:

    标签: r sorting vector attributes names


    【解决方案1】:

    您可以sortorder 名称:

    vct[sort(names(vct))]
    #vct[order(names(vct))]
    
    #     a11      a65       b2       c1      d66 
    #    "71" "orange"  "apple"     "67"     "88" 
    

    【讨论】:

    • 谢谢!这真的很有帮助。如果我想要一个位置,你知道我该怎么做,比如 b2 "apple" 是第一个,其余的按字母顺序排列吗?
    • 我不确定我是否理解。您可以将其添加为新问题吗?
    • 在这里发布了我的问题stackoverflow.com/questions/64889260/…
    猜你喜欢
    • 2014-04-10
    • 1970-01-01
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    • 2021-03-20
    • 2020-09-12
    • 1970-01-01
    相关资源
    最近更新 更多