Home > Mobile >  Arrange elements truely randomly by row
Arrange elements truely randomly by row

Time:06-20

I want to randomly arrange the elements in my data frame by rows. However, at the moment the arrangement is not really random because the elements of x2 and x3 can only appear at positions 1:18 and 19:36 respectively. How can I change my code so that the elements can show up at any position?

# Parameter
n_row <- 6
n_col <- 6
pch <- 1:11
col <- 1:8

# Randomly arrange elements by row
x1 <- setNames(expand.grid(pch, col), c("pch", "col"))
x2 <- x1[sample(seq_len(nrow(x1)), n_row*n_col*.5), ]
x3 <- x2[sample(1:nrow(x2)), ]
final <- sample(rbind(x2, x3))

CodePudding user response:

You might try sampleing the repeated sample.

set.seed(42)
res <- x1[sample(rep(sample(seq_len(nrow(x1)), 6*6*.5), 2)), ]

Check the result using table

table(res)
#     col
# pch  1 2 3 4 5 6 7 8
#   1  0 0 0 2 0 0 0 0
#   2  0 0 2 0 0 0 0 0
#   3  2 0 2 2 2 0 0 0
#   4  0 0 2 2 0 0 0 0
#   5  2 0 2 0 2 0 2 0
#   7  0 2 0 0 0 0 0 0
#   8  0 0 0 2 0 0 2 0
#   9  0 2 0 0 0 0 0 0
#   10 0 0 0 0 0 2 0 0
#   11 0 0 0 0 0 0 0 2

or if they all are either 0 or 2.

all(table(res) %in% c(0, 2))
# [1] TRUE

Data:

x1 <- expand.grid(pch=1:11, col=1:8)
  • Related