代码之家  ›  专栏  ›  技术社区  ›  Adrian

R:如何按名称重新排序向量元素

  •  1
  • Adrian  · 技术社区  · 7 年前
    s <- c("West", "North", "South", "East")
    

    我有一个向量,有4个元素。我想对它们重新排序,使向量包含 "North", "South", "West", "East" .我知道通过以下索引重新排序它们的一种方法。

    s[c(2, 3, 1, 4)]
    

    但有没有办法按名称重新订购?有点像 s["North", "South", "West," "East"] (不起作用)。注意,向量中的每个元素都是唯一的。

    1 回复  |  直到 7 年前
        1
  •  3
  •   MKR    7 年前

    虽然我不确定它是否符合你的目的,但有一个选择是将你的向量转换为 ordered 因素,然后 sort 它。

    s <- c("West", "North", "South", "East")
    
    
    s <- ordered(s, c("North", "South", "West", "East"))  #Define the order in which you want it
    
    s <- sort(s)  #Now sort vector. This could have been done as part of previous step itself
    
    s
    # [1] North South West  East 
    # Levels: North < South < West < East
    
    推荐文章