Home > database >  Randomizing within and across groups using group_by and sample
Randomizing within and across groups using group_by and sample

Time:05-15

I'm running a study in which each participant will be presented with stimuli that have been randomized at two different levels: blocks (3 unique blocks) and trials (4 unique trials per block) within blocks. So I am trying to create a data frame with a pre-randomized stimulus presentation list by:

  1. Randomly order the trials within each block
  2. Randomly order the blocks within participant.

--

df <- df %>% 
  group_by(id, block) %>% 
  mutate(trial = trial[sample(row_number())])

The trials randomize within block (and participant) but how do I then randomize the blocks within participant?

The data frame looks like this:

id block trial
n1 b 1
n1 b 2
n1 b 3
n1 b 4
n1 p 1
n1 p 2
n1 p 3
n1 p 4
n1 s 1
n1 s 2
n1 s 3
n1 s 4
n2 b 1
n2 b 2
n2 b 3
n2 b 4
n2 p 1
n2 p 2
n2 p 3
n2 p 4
n2 s 1
n2 s 2
n2 s 3
n2 s 4
n3 b 1
n3 b 2
n3 b 3
n3 b 4
n3 p 1
n3 p 2
n3 p 3
n3 p 4
n3 s 1
n3 s 2
n3 s 3
n3 s 4

CodePudding user response:

How about something like this:

dat <- structure(list(id = c("n1", "n1", "n1", "n1", "n1", "n1", "n1", 
"n1", "n1", "n1", "n1", "n1", "n2", "n2", "n2", "n2", "n2", "n2", 
"n2", "n2", "n2", "n2", "n2", "n2", "n3", "n3", "n3", "n3", "n3", 
"n3", "n3", "n3", "n3", "n3", "n3", "n3"), block = c("b", "b", 
"b", "b", "p", "p", "p", "p", "s", "s", "s", "s", "b", "b", "b", 
"b", "p", "p", "p", "p", "s", "s", "s", "s", "b", "b", "b", "b", 
"p", "p", "p", "p", "s", "s", "s", "s"), trial = c(1L, 2L, 3L, 
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 
4L)), row.names = c(NA, 36L), class = "data.frame")
library(dplyr)
library(tidyr)
dat %>% group_by(id, block) %>% 
  summarise(trial = list(sample(trial, n(), replace=FALSE))) %>%  
  group_by(id) %>% 
  slice_sample(n=3) %>% 
  unnest(trial)
#> `summarise()` has grouped output by 'id'. You can override using the `.groups`
#> argument.
#> # A tibble: 36 × 3
#> # Groups:   id [3]
#>    id    block trial
#>    <chr> <chr> <int>
#>  1 n1    b         4
#>  2 n1    b         1
#>  3 n1    b         2
#>  4 n1    b         3
#>  5 n1    s         2
#>  6 n1    s         4
#>  7 n1    s         3
#>  8 n1    s         1
#>  9 n1    p         4
#> 10 n1    p         3
#> # … with 26 more rows

Created on 2022-05-13 by the reprex package (v2.0.1)

  • Related