I would like R to sample a random row from any of K subarrays. I know how this is done with a single subarray, but each time I run my routine, R always samples from the last subarray, instead of randomly each time. I have not been able to find a simple workaround after fiddling with it for a while.
The issue relates to the following code:
K <- 2 # number of subarrays
N <- 10
Hstar <- 10
perms <- 10
specs <- 1:N
pop <- array(dim = c(c(perms, N), K))
haps <- as.character(1:Hstar)
probs <- rep(1/Hstar, Hstar)
for(j in 1:perms){
for(i in 1:K){
pop[j, specs, i] <- sample(haps, size = N, replace = TRUE, prob = probs)
}
}
HAC.mat <- array(dim = c(c(perms, N), K))
for(k in specs){
for(j in 1:perms){
for(i in 1:K){
ind.index <- sample(specs, size = k, replace = FALSE)
hap.plot <- pop[sample(1:nrow(pop), size = 1, replace = TRUE), ind.index, i] # I believe the issue lies here
HAC.mat[k, j, i] <- length(unique(hap.plot))
}
}
}
In the above routine, hap.plot always contains a random row from the last subarray instead of a subarray selected at random each time the simulation is run. For example, what I want is for the simulation to sample a row from any of the two subarrays randomly: subarray 2, run again, subarray 2, run again, subarray 1, etc.
I am unsure how to accomplish what I need. I have tried sample() with no success. The fix I believe would have to be in hap.plot.
Any ideas?
Aucun commentaire:
Enregistrer un commentaire