You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在RStudio中生成含随机顺序双区块的模拟数据集

硕士论文功效分析:符合研究设计的模拟数据集生成方案

需求说明

需要生成满足以下两个条件的模拟数据集:

  1. target变量规则:8个故事划分为2个各含4个故事的区块,区块顺序随机,每个区块内的target值统一为-1或1
  2. action变量规则:每个被试恰好看到4次-1和4次1,呈现顺序随机

问题诊断

你尝试的代码中,target_pattern和target_order的逻辑错误,导致每个被试的target值完全一致,无法实现区块化的变量设置。

解决方案代码

set.seed(1234) # 固定随机种子保证结果可重复

n_participants <- 50
n_stories <- 8
b0 <- 0 # 假设截距项为0,可根据实际需求修改

# 生成每个被试的target序列:2个4故事区块,区块顺序随机,区块内target统一
target_list <- lapply(1:n_participants, function(x) {
  # 随机决定两个区块的target值(一个-1,一个1)
  block_values <- sample(c(-1, 1), size = 2, replace = FALSE)
  # 随机决定区块顺序
  block_order <- sample(c(rep(block_values[1], 4), rep(block_values[2], 4)))
  return(block_order)
})
target_vector <- unlist(target_list)

# 生成每个被试的action序列:恰好4个-1和4个1,顺序随机
action_list <- lapply(1:n_participants, function(x) {
  sample(c(rep(-1, 4), rep(1, 4)), size = 8, replace = FALSE)
})
action_vector <- unlist(action_list)

# 构建最终数据集
simulated_data <- data.frame(
  subj = rep(1:n_participants, each = n_stories),
  story = rep(1:n_stories, times = n_participants),
  group = rep(sample(c(-1, 1), size = n_participants, replace = TRUE), each = n_stories),
  target = target_vector,
  action = action_vector,
  interc = rep(b0, n_participants * n_stories)
)

代码关键逻辑解释

  • target变量生成:通过lapply为每个被试单独生成序列:先随机分配两个区块的target值(确保一个-1一个1),再打乱区块顺序,保证每个被试的8个故事是两个4故事的随机区块,每个区块内target统一。
  • action变量生成:同样用lapply为每个被试生成包含4个-1和4个1的随机打乱序列,满足每个被试的次数要求。
  • 保留原代码中group和interc的生成逻辑,保证与原有设计一致。

内容的提问来源于stack exchange,提问作者cjasmin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 20:05:22