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

我有这个很普通的任务。我想通过支出获得前十名的公司,并将其他公司总结为“其他”。我知道可以通过将行更改为因子变量然后对级别进行重新排序来手动对行进行重新排序,但这是行不通的,因为其他人始终可以位于不同的位置,并且我必须对许多市场进行此操作许多不同的国家。因此,“Others”应该始终位于和的最后位置,无论类别在中位于哪一行。我怎么做?

最佳答案

您也可以尝试:

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

关于r - R dplyr-动态排列行顺序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56422961/

10-10 13:27