首页 > 解决方案 > 有没有一种简单的方法可以将多个名称更改为 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 个颜色名称)。有没有更简单的方法来做到这一点?就像可能 negate() 或使用!在某处的代码中?比如说如果它不是黑色、棕色或红色变为其他?

标签: rdplyrcase-when

解决方案


您可以使用替换颜色%in%

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

也可以使用fct_otherfrom forcats

library(dplyr)
library(forcats)

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

推荐阅读