How can I randomly sample the color order of 368 images using 4 colors that
Based on this, I have already managed the sampling without direct repetition:
library("dplyr")
set.seed(340)
values <- c("blue", "red", "green", "yellow")
len <- 368 # number of samples
samp <- sample(values, 1) # initialise variable
cols <- sapply(2:len, function(i) samp[i] <<- sample(setdiff(values, samp[i-1]), 1, replace = TRUE))
table(cols) # colors appear 94, 92, 88, 93 times
I tried building a for-loop that samples until the exact numbers are reached with if(table(cols)[1:4] == 92), but it didn't work and after doing a lot of research, I still don't know how to proceed. I would be really thankful for tips and help!
You can use a Markov chain.
library(markovchain)
# states
statesNames <- c("blue", "red", "green", "yellow")
# transition matrix: each state can go to another state with probability 1/3
tmatrix <- rbind(
c(0, 1/3, 1/3, 1/3),
c(1/3, 0, 1/3, 1/3),
c(1/3, 1/3, 0, 1/3),
c(1/3, 1/3, 1/3, 0)
)
# Markov chain
chain <- new("markovchain", states = statesNames, transitionMatrix = tmatrix)
# sample the Markov chain
rmarkovchain(n = 10, chain)
# "red" "green" "red" "yellow" "red" "yellow" "red" "blue" "yellow" "blue"
The graph of the Markov chain:
plot(chain)

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With