Home > Back-end >  Randomizing a sample by selected groups in R
Randomizing a sample by selected groups in R

Time:03-12

In my dataset, 90 people (samples) must each play two types of game, of a total of four types: X, Y, Z and W. I would like to randomize in R which games each person will play, as well as the game order, so that it follows this way:

UA First game Second game
Person 1 Game X Game W
Person 2 Game W Game Y
Person 3 Game Z Game W

Thus, each game must be played by the same number of people (i.e., 30 people per game), and game W must be played by everyone. Is there a simple way to do this in R?

CodePudding user response:

  1. create vector that contains 30 reps of games X, Y, Z
  2. create random permutation of that vector
  3. to each game add game W
  4. permute each game pair
games <- t(
  apply(
    data.frame(
      first_game = sample(rep(c("X", "Y", "Z"), 30), 90),
      second_game = "W"
    ),
    1,
    function(x) sample(x, 2)
  )
)

games <- cbind(paste("pearson", 1:90), games)
colnames(games) <- c("UA" ,"first_game", "second_game")
games <- as.data.frame(games)
  • Related