【发布时间】:2021-03-15 11:56:58
【问题描述】:
我有一个包含马的数据集,并希望根据毛色对它们进行分组。在我的数据集中使用了 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 |
相反,我得到下面的数据(第二个表),其中未知和其他被切换。
| 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"
那么我做错了什么/错过了什么?提前致谢。
【问题讨论】: