使用正则表达式批量重编码多因子:dplyr::recode正则失效问题求助
批量正则重编码问卷回答的解决方案
问题背景
我有一份问卷数据,部分问题的回答格式为「I am certain that [主题]」「I think it is possible that [主题]」等,需要按以下规则将回答转换为数值:
- "I am certain that" → 1
- "I think it is possible that" → 2
- "I don't know if is possible that" → 3
- "I think it is not possible that" → 4
- "I am certain that it is not possible that" → 5
- "It is impossible for me to know if" → 6
使用dplyr::recode尝试批量处理所有Q开头的列时,因该函数不支持正则表达式匹配,导致结果全部为NA,无法实现批量编码。
示例数据生成代码:
set.seed(12345) possible_answers <- c( "I am certain that", "I think it is possible that", "I don't know if is possible that", "I think it is not possible that", "I am certain that it is not possible that", "It is impossible for me to know if" ) num_answers <- 10 survey <- data.frame( Q1 = paste( sample(possible_answers, num_answers, replace = TRUE), "topic 1" ), Q2 = paste( sample(possible_answers, num_answers, replace = TRUE), "topic 2" ), Q3 = paste( sample(possible_answers, num_answers, replace = TRUE), "topic 3" ), Q4 = paste( sample(possible_answers, num_answers, replace = TRUE), "topic 4" ), Q5 = paste( sample(possible_answers, num_answers, replace = TRUE), "topic 5" ) )
解决方法
方法1:stringr::str_replace_all + 正则匹配
先创建正则匹配规则的命名向量,再批量处理目标列:
library(dplyr) library(stringr) # 定义正则匹配规则,^锚定字符串开头确保匹配前缀 recode_rules <- c( "^I am certain that.*" = "1", "^I think it is possible that.*" = "2", "^I don't know if is possible that.*" = "3", "^I think it is not possible that.*" = "4", "^I am certain that it is not possible that.*" = "5", "^It is impossible for me to know if.*" = "6" ) # 批量处理Q开头的列,转换为数值型 survey_recoded <- survey %>% mutate(across(starts_with("Q"), ~ as.numeric(str_replace_all(., recode_rules)))) # 查看结果 survey_recoded
方法2:dplyr::case_when + str_detect
通过逻辑判断匹配前缀,直观对应编码规则:
library(dplyr) library(stringr) survey_recoded <- survey %>% mutate(across(starts_with("Q"), ~ case_when( str_detect(., "^I am certain that") ~ 1, str_detect(., "^I think it is possible that") ~ 2, str_detect(., "^I don't know if is possible that") ~ 3, str_detect(., "^I think it is not possible that") ~ 4, str_detect(., "^I am certain that it is not possible that") ~ 5, str_detect(., "^It is impossible for me to know if") ~ 6, TRUE ~ NA_real_ # 处理未匹配的异常情况 ))) survey_recoded
方法3:提取前缀后用recode匹配
利用原有的前缀列表提取回答前缀,再进行编码:
library(dplyr) library(stringr) survey_recoded <- survey %>% mutate(across(starts_with("Q"), ~ { # 从回答中提取前缀(匹配possible_answers中的任意项) prefix <- str_extract(., paste0("^(", paste(possible_answers, collapse = "|"), ")")) # 用recode匹配对应的数值 recode(prefix, "I am certain that" = 1, "I think it is possible that" = 2, "I don't know if is possible that" = 3, "I think it is not possible that" = 4, "I am certain that it is not possible that" = 5, "It is impossible for me to know if" = 6) })) survey_recoded
内容的提问来源于stack exchange,提问作者nico
相关产品推荐
相关产品推荐

