【问题标题】:Is there a simple way to change multiple names to one single name in R?有没有一种简单的方法可以将多个名称更改为 R 中的一个名称?
【发布时间】: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)'

标签: r dplyr case-when


【解决方案1】:

您可以使用 %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')))

【讨论】:

    猜你喜欢
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 2012-02-25
    • 1970-01-01
    相关资源
    最近更新 更多