The below R code fills an array of specified dimensions with positive integers generated randomly via a probability vector.
subset.haps <- NULL
haps <- 1:4
num.specs <- 100
probs <- rep(1/4, 4)
perms <- 10000
K <- 1
gen.perms <- function() {
if (is.null(subset.haps)) {
sample(haps, size = num.specs, replace = TRUE, prob = probs)
} else {
resample <- function(x, ...) x[sample.int(length(x), ...)]
resample(subset.haps, size = num.specs, replace = TRUE, prob = probs[subset.haps])
}
}
pop <- array(dim = c(perms, num.specs, K))
for (i in 1:K) {
pop[, , i] <- replicate(perms, gen.perms())
}
However, profiling the above code suggests that improvements can be made.
The 'for' loop can be eliminated using rep()
rep(replicate(perms, gen.perms()), K)
However, this method does not produce an array, nor preserves array dimensions.
Of course, wrapping the above modified code within as.array() will fix the second issue, but the output does not resemble a typical array in structure.
My question
How can I ensure the array structure (i.e., dimensions) is preserved?