有没有一种简单的方法可以将多个名称更改为 R 中的一个名称?

Is there a simple way to change multiple names to one single name in R?

这是我的数据框的简化版。有颜色的列是字符。

|ID|Color |
|--|------| 
|1 |Brown |
|2 |Black |
|3 |Red   |
|4 |Blue  |
|5 |Black |
|6 |Green |
|7 |Brown |
|8 |Red   |
|9 |Yellow|
|10|Violet|

我想将所有不是黑色、棕色或红色的颜色替换为其他颜色。我有一段有效的代码。

library(tidyverse)
df_clean <- df %>%
   mutate(Color = case_when(
      str_detect(Color, "Red") ~ "Other",
      str_detect(Color, "Blue") ~ "Other",
      str_detect(Color, "Green") ~ "Other",
      str_detect(Color, "Yellow") ~ "Other",
      str_detect(Color, "Violet") ~ "Other",
      TRUE ~ Color
))

但我必须对所有颜色都这样做(我的完整数据集在 >160000 个数据条目中有超过 50 个颜色名称)。有没有更简单的方法来做到这一点?就像否定()或使用!在某处的代码中?比如说如果它不是黑色、棕色或红色改为其他?

您可以使用 %in%

替换颜色
df$Color[!df$Color %in% c('Black', 'Brown', 'Red')] <- 'Other'

也可以使用 forcats 中的 fct_other

library(dplyr)
library(forcats)

df %>% mutate(Color = fct_other(Color, c('Black', 'Brown', 'Red')))