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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With