How to Vectorize Nested Loop in R?

(This article was first published on Quantitative Finance Collector, and kindly contributed to R-bloggers)

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 - ,
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 his blog: Quantitative Finance Collector.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.