【问题标题】:R - Conditionally sort multiple columns as ascending or descending by groupR - 有条件地按组对多列进行升序或降序排序
【发布时间】:2018-02-22 09:10:09
【问题描述】:

我以前没有遇到过这个问题。我想根据条件对组内的多个列进行升序或降序排序

library(dplyr)
data <- mtcars %>% select(mpg, cyl, disp)

如果cyl &lt;= 4,我想按升序对mpg, disp(按该优先级)进行排序。如果cyl &gt; 4,我想按降序对mpg, disp 进行排序。

expected <- rbind(
    filter(data, cyl <= 4) %>% arrange(mpg, disp),
    filter(data, cyl > 4) %>% arrange(cyl, desc(mpg), desc(disp))
)

【问题讨论】:

  • 您的expected 解决方案看起来很合理。您希望从中改进什么?
  • 我的真实数据有很多组,条件并不总是与分组列相关 - 根据您的评论,我意识到我总是可以根据多个条件过滤我的 data.frame 并相应地安排。仍然希望有一个“更好”的方式

标签: r sorting


【解决方案1】:

将每个可能反转的变量乘以sign(4.1 - cyl)

mtcars %>% arrange(cyl, sign(4.1 - cyl) * mpg, sign(4.1 - cyl) * disp)

如果mpg 不是数字,则仍然可以通过将mpg 替换为xtfrm(mpg) 来实现,这会将其映射到数字。见?xtfrm

【讨论】:

    【解决方案2】:

    我们可以将值转换为负数以创建新列,然后对这些列进行排序。

    library(dplyr)
    
    data2 <- data %>%
      mutate_at(vars(mpg, cyl), funs(ifelse(cyl <= 4, ., -.))) %>%
      arrange(cyl, mpg2, disp2) %>%
      select(-ends_with("2"))
    data2
    #     mpg cyl  disp
    # 1  21.4   4 121.0
    # 2  21.5   4 120.1
    # 3  22.8   4 108.0
    # 4  22.8   4 140.8
    # 5  24.4   4 146.7
    # 6  26.0   4 120.3
    # 7  27.3   4  79.0
    # 8  30.4   4  75.7
    # 9  30.4   4  95.1
    # 10 32.4   4  78.7
    # 11 33.9   4  71.1
    # 12 21.4   6 258.0
    # 13 21.0   6 160.0
    # 14 21.0   6 160.0
    # 15 19.7   6 145.0
    # 16 19.2   6 167.6
    # 17 18.1   6 225.0
    # 18 17.8   6 167.6
    # 19 19.2   8 400.0
    # 20 18.7   8 360.0
    # 21 17.3   8 275.8
    # 22 16.4   8 275.8
    # 23 15.8   8 351.0
    # 24 15.5   8 318.0
    # 25 15.2   8 304.0
    # 26 15.2   8 275.8
    # 27 15.0   8 301.0
    # 28 14.7   8 440.0
    # 29 14.3   8 360.0
    # 30 13.3   8 350.0
    # 31 10.4   8 472.0
    # 32 10.4   8 460.0
    

    【讨论】:

    • 不错的方法 --
    猜你喜欢
    • 2018-11-30
    • 2018-05-03
    • 2016-10-18
    • 1970-01-01
    • 2015-08-30
    • 2020-11-09
    • 2021-07-06
    • 1970-01-01
    相关资源
    最近更新 更多