【发布时间】:2021-02-16 08:35:11
【问题描述】:
这是我的数据框的简化。带颜色的列是字符。
|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() 或使用!在某处的代码中?比如说如果它不是黑色、棕色或红色变为其他?
【问题讨论】:
-
看看
?"%in%"。否定可以用! -
在基础 R 中是'ifelse(!Color %in% c(“black”,”brown”,”red”),”Other”,Color)'