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

时间:2021-02-16 08:35:11

标签: r mutate case-when

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

|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() 或使用 !在某处的代码中?比如说如果不是黑色,棕色或红色变成其他?

1 个答案:

答案 0 :(得分:1)

您可以使用 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <nav></nav> <main></main> <footer></footer> </body> <style> *{ margin: 0; padding: 0; box-sizing: border-box; } body{ min-height: 100vh; } nav,main,footer{ padding: 1em; } nav{ background-color: yellow; } main{ background-color: rgb(0, 82, 171); flex-grow: 1; } footer{ background-color: green; } body{ display: flex; flex-direction: column; } </style> </html>

替换颜色
%in%

也可以使用 df$Color[!df$Color %in% c('Black', 'Brown', 'Red')] <- 'Other' 中的 fct_other

forcats