Is there a way to assign vector elements to multiple subarrays in R, using sample() or split() (or a combination of both functions)?
Essentially what I need is a function that randomly assigns values to multiple subarrays
Here's my full specific code:
K <- 2 # number of subarrays
N <- 100
Hstar <- 10
perms <- 10000
probs <- rep(1/Hstar, Hstar)
K1 <- c(1:5)
K2 <- c(6:10)
specs <- 1:N
pop <- array(dim = c(c(perms, N), K))
haps <- as.character(1:Hstar)
for(j in 1:perms){
for(i in 1:K){
if(i == 1){
pop[j, specs, i] <- sample(haps, size = N, replace = TRUE, prob = probs)
} else{
pop[j,, 1] <- sample(haps[K1], size = N, replace = TRUE, prob = probs[K1])
pop[j,, 2] <- sample(haps[K2], size = N, replace = TRUE, prob = probs[K2])
}
}
}
pop[j,, 1] is the first subarray in pop, while pop[j,, 2] is the second subarray in pop
If I have 20 subarrays, using sample() 20 times is tedious. I just want a way to assign values to the any number of subarrays quickly and easily.
Any ideas?
It depends whether you want replacement (the possibility of duplicate/omitted elements). Regardless, it's a one liner
sample(x,length(x),replace=FALSE)
Not 100% clear on the whole multiple subarray thing, but my approach would be something like:
num.intervals<-5
interval.size<-length(x)/5 #need to make sure this is evenly divisible I suppose
arr.master<-rep(NA,0)
for (i in 1:num.intervals){
arr.master<-rbind(arr.mater,sample(x,interval.size,replace=TRUE)
}
Basically, just take samples and keep mashing them together? Would this accomplish your goal?
Do you want to have the sum of num_elements of all subarrays equal to num_elements in the original array? If so, then it's just a random sorting problem (really easy) and then cut it up after into any number of subarrays. If not, then you could fix the number of elems in all subarrays in advance; randomly sample from original a new vector of this size; then partition it into arbitrary subarrays.