R语言修正数据集字段拼写错误的方法求助
修正数据集mat_source列的拼写错误
问题背景
我的数据集Inventory的mat_source字段应仅包含3种固定值:ark、bg、brnl,但录入时出现拼写错误。通过以下R代码查看了列的唯一值及对应计数:
glimpse(Inventory) # Rows: 4,860 # Columns: 5 # asset_ID <dbl> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 3… # length <dbl> 500, 170, 480, 284, 30, 500, 270, 476, 395, 80, 500, 500, 500, 110, 500, 363, 254, 113, 500, 200, 27, 583, 5… # age <dbl> 6.120548, 5.967123, 8.824658, 9.824658, 3.808219, 3.095890, 6.797260, 2.816438, 4.975342, 18.904110, 14.1315… # mat_source <chr> "ark", "bg", "brnl", "brnl", "bg", "brnl", "brnl", "ark", "brnl", "ark", "brnl", "ark", "ark", "brnl", "brnl"… # con_num <dbl> 1, 1, 2, 2, 3, 1, 4, 4, 1, 2, 1, 1, 4, 3, 1, 4, 3, 3, 1, 3, 2, 2, 1, 3, 3, 3, 1, 3, 4, 3, 4, 4, 2, 3, 3, 3, … # 查看唯一值 unique(Inventory$mat_source) # [1] "ark" "bg" "brnl" "arl" "arkm" "black" # 按mat_source分组计数 Inventory %>% group_by(mat_source) %>% summarise(Count = n()) # A tibble: 6 × 2 # mat_source Count # <chr> <int> # 1 ark 1394 # 2 arkm 6 # 3 arl 1 # 4 bg 1361 # 5 black 4 # 6 brnl 2094
需要将arkm、arl替换为ark,black替换为bg,但之前尝试的方法未成功:
# 错误:fct_recode参数顺序颠倒,应为"正确值" = "错误值" mutate(Inventory, mat_source = fct_recode(mat_source, "arl" = "ark")) # 错误:仅处理了arl,且替换值写错为alk,后续因子转换逻辑无效 Inventory$mat_source <- ifelse(Inventory$mat_source == "arl", "alk", Inventory$mat_source) Inventory <- Inventory %>% mutate(mat_source = factor(mat_source, levels = mat_source))
正确处理方法
方法1:使用fct_recode(因子重编码)
注意fct_recode的参数顺序是**"目标值" = "原始错误值"**,需覆盖所有错误项:
library(forcats) library(dplyr) Inventory <- Inventory %>% mutate(mat_source = fct_recode(mat_source, "ark" = "arl", "ark" = "arkm", "bg" = "black"))
方法2:使用case_when(灵活条件替换)
逻辑清晰,适合多条件判断场景:
Inventory <- Inventory %>% mutate(mat_source = case_when( mat_source %in% c("arl", "arkm") ~ "ark", mat_source == "black" ~ "bg", TRUE ~ mat_source # 保留原本正确的取值 ))
方法3:使用recode(针对字符型列)
若mat_source是字符型而非因子,直接用dplyr::recode:
Inventory <- Inventory %>% mutate(mat_source = recode(mat_source, "arl" = "ark", "arkm" = "ark", "black" = "bg"))
验证结果
执行替换后,再次检查唯一值和计数确认修正效果:
unique(Inventory$mat_source) # 应仅返回 "ark" "bg" "brnl" Inventory %>% group_by(mat_source) %>% summarise(Count = n()) # 预期结果: # mat_source Count # <chr> <int> # 1 ark 1401 # 1394+6+1 # 2 bg 1365 # 1361+4 # 3 brnl 2094
内容的提问来源于stack exchange,提问作者Natalie Storm
相关产品推荐
相关产品推荐

