How to Vectorize Nested Loop in R?

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?.

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.