R语言中结合case_when与lag()填充行为实验Response行编码
R 行为任务编码自动替换实现方案
前置说明
假设你的原始数据框命名为behav_df,包含至少2个核心列:
Code:记录刺激/反应编码,Response行对应值为NAAccuracy:记录目标反应准确率,1=正确,0=错误
实现逻辑
你提到的编码规则可以简化为统一计算公式,无需重复写判断条件:
新编码 = (目标刺激Code - 7) * 2 + 15 + (1 - 准确率)
验证:目标7正确时=(0)*2+15+0=15,错误时=15+1=16,完全匹配你的需求。
完整可运行代码
首先加载依赖包(如果没安装先运行install.packages("tidyverse")):
library(tidyverse) # 方法1:适用于每试次固定9行的情况(1前置+1启动+1目标+1后置+5Response=9行) result_df <- behav_df %>% # 给每个试次分配唯一ID mutate(trial_id = ceiling(row_number()/9)) %>% # 按试次分组,提取当前试次的目标编码和对应准确率 group_by(trial_id) %>% mutate( # 提取当前试次的目标刺激Code(7-12之间的数值) target_code = Code[between(Code,7,12)], # 提取当前试次的目标准确率 target_acc = Accuracy[between(Code,7,12)] ) %>% ungroup() %>% # 替换Response行的NA编码 mutate( Code = case_when( is.na(Code) ~ (target_code -7)*2 +15 + (1 - target_acc), TRUE ~ Code ) ) %>% # 删除临时生成的辅助列 select(-trial_id, -target_code, -target_acc) # 方法2:如果试次行数不固定,用前置掩码Code=13作为新试次开始的标记 result_df <- behav_df %>% # 遇到Code=13就生成新的试次ID mutate(trial_id = cumsum(Code == 13)) %>% # 后续步骤和方法1完全一致 group_by(trial_id) %>% mutate( target_code = Code[between(Code,7,12)], target_acc = Accuracy[between(Code,7,12)] ) %>% ungroup() %>% mutate( Code = case_when( is.na(Code) ~ (target_code -7)*2 +15 + (1 - target_acc), TRUE ~ Code ) ) %>% select(-trial_id, -target_code, -target_acc)
验证方法
你可以先抽取前2个试次的数据测试输出是否符合预期:
# 查看前18行(2个试次)的结果 head(result_df, 18)
确认Code列的NA已经被替换为对应的15-26编码,且原有编码(1-14)保持不变,时序和原始数据完全一致,可直接用于后续分析。
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

