如何在R中基于两列信息生成指定映射的新列?
R语言实现trialtype与condition列的映射合并
方法一:使用dplyr的case_when函数
这种方法直接通过条件判断完成映射,逻辑清晰,适合规则明确的场景:
首先加载dplyr包(未安装的话先运行install.packages("dplyr")):
library(dplyr) # 原始数据 example <- data.frame( sub = c(101, 101, 101, 102, 102, 102), trialtype = c("ReframeNeg", "ImmerseNeu", "ImmerseNeg", "ImmerseNeu", "ImmerseNeg", "ReframeNeg"), condition = c("Self", "Self", "Self", "Other", "Other", "Other") ) # 创建新列并完成映射 example_solution <- example %>% mutate(trial = case_when( condition == "Self" & trialtype == "ReframeNeg" ~ "selfrefneg", condition == "Self" & trialtype == "ImmerseNeg" ~ "selfimmneg", condition == "Self" & trialtype == "ImmerseNeu" ~ "selfimmneut", condition == "Other" & trialtype == "ReframeNeg" ~ "socrefneg", condition == "Other" & trialtype == "ImmerseNeg" ~ "socimmneg", condition == "Other" & trialtype == "ImmerseNeu" ~ "socimmneut" ))
方法二:使用自定义映射表匹配
如果后续需要修改映射规则,这种方法更灵活,只需调整映射表即可:
# 原始数据 example <- data.frame( sub = c(101, 101, 101, 102, 102, 102), trialtype = c("ReframeNeg", "ImmerseNeu", "ImmerseNeg", "ImmerseNeu", "ImmerseNeg", "ReframeNeg"), condition = c("Self", "Self", "Self", "Other", "Other", "Other") ) # 定义映射规则 map_rules <- c( "SelfReframeNeg" = "selfrefneg", "SelfImmerseNeg" = "selfimmneg", "SelfImmerseNeu" = "selfimmneut", "OtherReframeNeg" = "socrefneg", "OtherImmerseNeg" = "socimmneg", "OtherImmerseNeu" = "socimmneut" ) # 先合并列,再匹配映射规则 example_solution <- example %>% mutate(combined = paste0(condition, trialtype), trial = map_rules[combined]) %>% select(-combined) # 移除临时合并的列
验证结果
运行上述代码后,执行print(example_solution)即可得到期望的输出:
sub trialtype condition trial 1 101 ReframeNeg Self selfrefneg 2 101 ImmerseNeu Self selfimmneut 3 101 ImmerseNeg Self selfimmneg 4 102 ImmerseNeu Other socimmneut 5 102 ImmerseNeg Other socimmneg 6 102 ReframeNeg Other socrefneg
内容的提问来源于stack exchange,提问作者jo_
相关产品推荐
相关产品推荐

