I want to make a random matrix with n rows and m columns. I want the elements of each row of the matrix to be randomly chosen from a set of numbers. I want to have at least one different number in each row. I don't want all the elements of a row to be the same. I once asked my question here, but I don't know why the function I was provided still gives me some rows with all the same elements. How can I adjust this function?
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)}
Here is an example:
x <- c(1, 1.5, 2, 3,4)
set.seed(123456)
matall=f2(x, 1200, 4)
View(matall)
[,1] [,2] [,3] [,4]
[1,] 3.0 3.0 1.5 1.5
[2,] 1.5 1.0 2.0 1.0
[3,] 4.0 1.0 3.0 2.0
[4,] 4.0 4.0 4.0 4.0