r - 有没有一种简单的方法可以将多个名称更改为 R 中的一个名称?
问题描述
这是我的数据框的简化。带颜色的列是字符。
|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%
df$Color[!df$Color %in% c('Black', 'Brown', 'Red')] <- 'Other'
也可以使用fct_other
from forcats
。
library(dplyr)
library(forcats)
df %>% mutate(Color = fct_other(Color, c('Black', 'Brown', 'Red')))
推荐阅读
- javascript - 使用 Javascript 的表格内容的正则表达式
- powershell - Azure DevOps 中的 PowerShell 任务出错:术语“powershell.exe”未被识别为名称
- python - GUI 在工作人员的睡眠中冻结
- xml - 如何在 Android Studio 中将我的 toolBar 和 NavigationView 与我的 TabLayout 合并?
- makefile - 我可以让删除中间文件吗?
- ios - 在 Swift 5 中将数据从 UIPickerView 传递到 UIViewController
- java - Append to File & Read from File, but nothing happens
- python-3.x - 将张量流数据集分离到张量流2中的不同输出
- sql - Postgres WHERE 两个数组有一个非空的交集
- c# - 无法从关系数据库 C# Visual Studio 2019 生成一个表的控制器