【问题标题】:Sort vector with character and number in R用R中的字符和数字对向量进行排序
【发布时间】:2016-08-04 14:55:18
【问题描述】:

我想对向量进行排序

m=c(1,"

仅按数字排序

输出如 (1,2,"

我在 gtools 库中尝试了混合排序,但它不起作用。

还有,有没有什么函数可以标记每个元素来自哪个向量?

例如,向量 m 中的数字为 0,向量 n 中的数字为 1

并获得类似 (0,1,0,1,0,0,1,...,1,1,1) 的输出

谢谢

【问题讨论】:

    标签: r


    【解决方案1】:

    我们将 'm' 和 'n' 的 names 设置为 '0' 和 '1',通过提取新向量中的数字部分(使用gsub) 转换为 numeric, order 它并使用该索引来订购“n1”。

    n1 <- c(setNames(m, rep(0, length(m))),setNames(n, rep(1, length(n))))
    r1 <- n1[order(as.numeric(gsub("\\D+", "", n1)))]
    
    as.vector(r1)
    #[1] "1"   "2"   "<4"  "<4"  "5"   "7"   "8"   "<12" "15"  "17"  "18"  "20"  
    #[13]  "<21" "<25" "25"  "27"  "34"  "<35" "40"  "43" 
    
    as.integer(names(r1))
    #[1] 0 1 0 1 0 0 1 0 0 1 0 1 0 0 1 0 1 1 1 1
    

    【讨论】:

      猜你喜欢
      • 2016-07-29
      • 1970-01-01
      • 1970-01-01
      • 2014-02-02
      • 2013-07-06
      • 2021-07-28
      • 1970-01-01
      • 1970-01-01
      • 2018-09-15
      相关资源
      最近更新 更多