str_detect 在 R 中重命名涂层颜色出错

Renaming coat colors in R goes wrong with str_detect

我有一个关于马的数据集,我想根据毛色对它们进行分组。在我的数据集中使用了超过 140 种颜色,我想返回到只有几种外套颜色并将其余颜色分配给其他颜色。但有些马的毛色没有登记,即未知。以下是新颜色应该是什么。 (为了说明这个问题,我有一个旧外套颜色和一个新外套颜色。但我只想更改外套颜色,而不是创建一个新的颜色列)

Horse ID Coatcolor(old) Coatcolor
1 black Black
2 bayspotted Spotted
3 chestnut Chestnut
4 grey Grey
5 cream dun Other
6 Unknown
7 blue roan Other
8 chestnutgrey Grey
9 blackspotted Spotted
10 Unknown

相反,我得到了下面的数据(第二个 table),其中 unknown 和 other 被切换了。

Horse ID Coatcolor
1 Black
2 Spotted
3 Chestnut
4 Grey
5 Unknown
6 Other
7 Unknown
8 Grey
9 Spotted
10 Other

我使用了下面的代码

mydata <- data %>%
  mutate(Coatcolor = case_when(
     str_detect(Coatcolor, "spotted") ~ "Spotted",
     str_detect(Coatcolor, "grey") ~ "Grey",
     str_detect(Coatcolor, "chestnut") ~ "Chestnut",
     str_detect(Coatcolor, "black") ~ "Black",
     str_detect(Coatcolor, "") ~ "Unknown",
     TRUE ~ Coatcolor
  ))
mydata$Coatcolor[!mydata$Coatcolor %in% c("Spotted", "Grey", "Chestnut", "Black", "Unknown")] <- "Other"

那我在做什么wrong/missing?提前致谢。

您可以使用dplyr包的recode功能。假设缺少的点是 NA,您随后可以使用 tidyr 包的 replace_na 将所有 NA 设置为“其他”。这取决于您丢失的数据点的格式。

mydata <- tibble(
  id = 1:10,
  coatcol = letters[1:10]
) 

mydata$coatcol[5] <- NA
mydata$coatcol[4] <- ""

mydata <- mydata %>%
  mutate_all(list(~na_if(.,""))) %>% # convert empty string to NA
  mutate(Coatcolor_old = replace_na(coatcol, "Unknown")) %>% #set all NA to Unknown
  mutate(Coatcolor_new = recode(
    Coatcolor_old,
    'spotted'= 'Spotted',
    'bayspotted' = 'Spotted',
    'old_name' = 'new_name',
    'a' = 'A', #etc.
  ))
mydata