R dplyr - 动态排序行顺序

3
df <- data.frame(
    company = c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "o", "p"),
    EUR = c(1000, 700, 200, 90, 120, 200, 90, 150, 120, 210, 100, 120, 200, 50, 70)
) 

df <- df %>%
    mutate(company = as.character(company)) %>%
    mutate(company = ifelse(row_number() > 10, "others", company)) %>%
    mutate(company = as.factor(company)) %>%
    group_by(company) %>%
    summarise(EUR = sum(EUR, na.rm = TRUE)) %>%
    arrange(desc(EUR))
df

# A tibble: 11 x 2
   company   EUR
   <fct>   <dbl>
 1 a        1000
 2 b         700
 3 others    540
 4 j         210
 5 c         200
 6 f         200
 7 h         150
 8 e         120
 9 i         120
10 d          90
11 g          90

我有一个很常见的任务,希望能获取支出前十的公司并将其他公司汇总为“其他”。我知道可以手动将行重新排序并更改为因子变量,然后重新排序级别,但这种方法不可行,因为“其他”始终可能位于不同位置,并且我必须在许多不同国家的许多市场中执行此操作。所以,“其他”应该始终位于最后一位不管类别在哪一行。我该怎么做?

2个回答

4

您也可以尝试:

df %>%
 arrange(company == "others", desc(EUR))

   company   EUR
   <fct>   <dbl>
 1 a        1000
 2 b         700
 3 j         210
 4 c         200
 5 f         200
 6 h         150
 7 e         120
 8 i         120
 9 d          90
10 g          90
11 others    540

1
你可以通过使用 slice 函数,找到 "others" 的行数并进行重新排列。
library(dplyr)

df %>%
  slice({i <- which.max(company == "others"); c(setdiff(seq_len(n()), i), i)})

#   company   EUR
#   <fct>   <dbl>
# 1 a        1000
# 2 b         700
# 3 j         210
# 4 c         200
# 5 f         200
# 6 h         150
# 7 e         120
# 8 i         120
# 9 d          90
#10 g          90
#11 others    540

相同的逻辑在基础R中是这样的:
i <- which.max(df$company == "others")
df[c(setdiff(seq_len(nrow(df)), i), i), ]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接