Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 790
Adrian Avatar asked Sep 03 '26 23:09

Adrian


1 Answers

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.

like image 76
ThomasIsCoding Avatar answered Sep 06 '26 13:09

ThomasIsCoding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!