Solution
t(replicate(20, sample(c(1, 1.2, sample(c(1, 1.2), 8, replace = TRUE)))))
Explanation
sample(c(1, 1.2, sample(c(1, 1.2), 8, replace = TRUE)))
creates a randomly ordered sample of 10 that ensures one of the elements will be 1, one of the elements will be 1.2, and the other 8 will be randomly selected from 1 and 1.2.
t(replicate(20, sample(c(1, 1.2, sample(c(1, 1.2), 8, replace = TRUE)))))
does this 20 times and transposes the answer to be of the dimensions you'd like.
UPDATE
After additional comments, it seems you need to be able to accomplish two different things:
- Create an n by m matrix randomly filled with the values of x subject to the constraint that each row of the resulting matrix contains every element of x at least once.
- Create an n by m matrix randomly filled with the values of x subject to the constraint that each row of the resulting matrix has more than one unique value.
So, at this point, I would recommend creating functions:
f1 <- function(x, n, m) {
N <- length(x)
if ( N > m ) {
stop('x is longer than the number of columns requested.', call. = FALSE)
}
return(t(replicate(n, sample(c(x, sample(x, m - N, replace = TRUE))))))
}
f2 <- function(x, n, m) {
if ( length(unique(x)) == 1 ) {
stop('x has only one unique element.', call. = FALSE)
}
result <- t(replicate(n, sample(x, m, replace = TRUE)))
while ( any(apply(result, 1, function(x) length(unique(result)) == 1)) ) {
result <- t(replicate(n, sample(x, m, replace = TRUE)))
}
return(result)
}
(If I were you I'd also give those functions more informative names).
f1()
accomplishes what my original answer does (corresponding to number 1. above) for arbitrary x
, n
, and m
. f2()
accomplishes the new request (corresponding to number 2. above); however, note there are probably better ways to accomplish this task, and this approach (a while
loop) could take an arbitrary amount of time depending on the values of x
, n
, m
, and chance. Here are example calls of the functions:
set.seed(1234)
x <- c(1, 1.2)
f1(x, 20, 10)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] 1.2 1.2 1.2 1.2 1.2 1.0 1.2 1.0 1.0 1.0
[2,] 1.0 1.0 1.0 1.0 1.0 1.2 1.0 1.0 1.0 1.2
[3,] 1.0 1.2 1.2 1.2 1.2 1.2 1.0 1.0 1.2 1.0
[4,] 1.2 1.0 1.2 1.0 1.2 1.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