Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 206235

Efficiently preserving array dimensions in R

$
0
0

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?


Viewing all articles
Browse latest Browse all 206235

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>