R语言双条件随机游走模拟器问题:条件交替逻辑修复求助
任务模拟器试次条件交替逻辑修复
问题根源
原代码循环逻辑错误:先完整执行条件1的100次试次,将结果写入Trial=1~100;接着执行条件2的100次试次,同样写入Trial=1~100,导致条件2的数据完全覆盖条件1,最终所有试次都显示条件2的配置。
需求是试次按**1→条件1、2→条件2、3→条件1、4→条件2...**的交替逻辑运行。
修复后的代码
#Set a seed set.seed(2024) #Variable declaration------------- nConds <- 2 #Number of conditions stim <- c("R", "L") #Stimulus labels pi <- c(.75, .65) #Probability of step (+1) for random walk; 1-pi will be the probability of stepping -1 diff <- c("Easy", "Hard") #Difficulty label for the condition mean_a <- c(40, 40) #Mean upper bound for each condition a_s <- c(0, 0) #Variability in upper bound for each condition zp=c(.5, .5) #Multiplier of a for starting point for condition (Z = a*zp) zp_s=c(0, 0) #Variability for starting point multiplier Nsubs=1 #Number of subjects Trials_total=100 #总试次数(交替后每个条件各执行50次) timeout=500 #Timeout parameter for the random walk #Create an empty dataframe for storing responses mydata=data.frame("Sub"=rep(1:Nsubs, each=Trials_total), "Trial"=rep(1:Trials_total, Nsubs), "RESPONSE"=NA, "RT"=NA, "Condition"=NA, "Stimulus"=NA) for (myperson in 1:Nsubs){ for (i in 1:Trials_total){ # 根据试次奇偶性交替选择条件:奇数试次用条件1,偶数用条件2 mycond <- ifelse(i %% 2 == 1, 1, 2) # 获取当前条件的参数 condpi=pi[mycond] cond_a=mean_a[mycond] cond_a_s=a_s[mycond] cond_zp=zp[mycond] cond_zp_s=zp_s[mycond] cond_stim=stim[mycond] cond_diff=diff[mycond] mytrial=i trial_a=rnorm(1, mean=cond_a, sd=cond_a_s) trial_Z=rnorm(1, mean=trial_a*cond_zp, sd=cond_zp_s) trial_Pi=rnorm(1, mean=condpi, sd=0) #Begin setup for random walk time=0 curpointer=trial_Z #Conduct random walk while (time < timeout){ time=time+1 curpointer=curpointer+sample(c(-1, 1), size=1, prob = c(1-trial_Pi, trial_Pi)) if (curpointer >= trial_a) { myresponse="1" break } else if (curpointer <= 0){ myresponse="0" break } } myRT=abs(time) #Save the parameters to the respective trial in the dataframe row_idx <- which(mydata$Sub==myperson & mydata$Trial==mytrial) mydata[row_idx,"RESPONSE"]=myresponse mydata[row_idx, "RT"]=myRT mydata[row_idx, "Condition"]=mycond mydata[row_idx, "Stimulus"]=cond_stim } }
关键修改点
- 循环结构调整:移除原有的条件外层循环,改为在试次循环内通过
i %% 2 == 1判断奇偶性,动态选择当前条件 - 变量命名优化:将
Trials_per_cond改为Trials_total,明确表示总试次数(交替逻辑下每个条件各执行50次) - 数据框初始化优化:提前声明
Condition和Stimulus列,避免后续赋值时自动转换类型 - 索引效率优化:用
which()提前定位目标行索引,替代重复的逻辑判断
修复后输出示例
|Sub|Trial|RESPONSE|RT |Condition|Stimulus| |1 |1 | 1 |102 | 1 | R | |1 |2 | 1 |111 | 2 | L | |1 |3 | 1 |65 | 1 | R | |...|... | ... |... | ... | ... | |1 |98 | 1 |98 | 2 | L | |1 |99 | 1 |120 | 1 | R | |1 |100 | 1 |100 | 2 | L |
内容的提问来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

