compbiostats
compbiostats

Reputation: 961

Efficiently preserving array dimensions in R

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?

Upvotes: 0

Views: 49

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173898

You just make pop then set its dim attribute afterwards:

pop <- rep(replicate(perms, gen.perms()), K)
dim(pop) <-  c(perms, num.specs, K)

And to prove it:

class(pop)
# [1] "array"
dim(pop)
# [1] 10000   100     1
pop[2020,23,1]
# [1] 2

Upvotes: 1

Related Questions