Adrian
Adrian

Reputation: 9793

How to parallelize while loops?

iter <- 1000
myvec <- c()
while(is.null(myvec) || nrow(myvec) <= iter){
 x = rnorm(10, mean = 0, sd = 1)
 if(sum(x) > 2.5){
    myvec <- rbind(myvec, x)
 }
}

I want to parallelize the above while loop, where I keep iterating until I have a total of iter = 1000 entries in myvec. I checked out this post here, but I don't think the answer there is applicable to my example.

Upvotes: 3

Views: 335

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 101024

Actually you don't need to parallelize the while loop. You can vectorize your operations over x like below

iter <- 1000
myvec <- c()
while (is.null(myvec) || nrow(myvec) <= iter) {
  x <- matrix(rnorm(iter * 10, mean = 0, sd = 1), ncol = 10)
  myvec <- rbind(myvec, subset(x, rowSums(x) > 2.5))
}
myvec <- head(myvec, iter)

or

iter <- 1000
myvec <- list()
nl <- 0
while (nl < iter) {
  x <- matrix(rnorm(iter * 10, mean = 0, sd = 1), ncol = 10)
  v <- subset(x, rowSums(x) > 2.5)
  nl <- nl + nrow(v)
  myvec[[length(myvec) + 1]] <- v
}
myvec <- head(do.call(rbind, myvec), iter)

which would be much faster even if you have large iter, I believe.

Upvotes: 4

Related Questions