How to Vectorize Nested Loop in R?

[This article was first published on Quantitative Finance Collector, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Could any R expert here help me to vectorize my for loop? Thanks in advance for your favor. The reason I am in trouble is the variable inside my “for” function are updated after each loop, which makes me feel difficult to use lapply, sapply or whatever.

Simplifed codes are listed below:

for (i in 1:N) { #N could be a large number, AdjS and VarS are initially given and updated for each i
        PredS <- F %*% AdjS                                                                              
        PredY <- H %*% PredS
        PredError <- (Y[i,] - t(PredY))
        VarY <- (H %*% VarS) %*% t(H)
        InvVarY <- solve(VarY)
        KG <- (VarS %*% t(H)) %*% InvVarY
        AdjS <- PredS + PredError
        VarS <- (diag(3) - KG %*% H) %*% VarS
        ll[i] <- PredError %*% InvVarY %*% t(PredError)
  }

The point is how to vectorize the for loop while allowing AdjS and VarS to be updated. I appreciate your help.
Tags – r , vectorize
Read the full post at How to Vectorize Nested Loop in R?.

To leave a comment for the author, please follow the link and comment on their blog: Quantitative Finance Collector.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)