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