Mar
12

## 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:

The point is how to vectorize the for loop while allowing AdjS and VarS to be updated. I appreciate your help.

Hot posts:

15 Incredibly Stupid Ways People Made Their Millions

Online stock practice

Value at Risk xls

Ino.com: Don't Join Marketclub until You Read This MarketClub Reviews

Bootstrapping interest rate curve

Random posts:

CONVERTIBLE BOND PRICING MODEL

Hull-White Term Structure Model

Up-and-out call option by Monte Carlo

Code search portal

Online Swap Valuation

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)

}

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.

**People viewing this post also viewed:**

Hot posts:

Random posts:

tmp<-100

start<-100

for (j in 1:4) {

i[j]<-start*tmp

tmp<-tmp/2

}

which is the same as:

tmp<-100

test<-function(x) {

tmp2<-x*tmp

tmp<<-tmp/2

return(tmp2)

}

sapply(1:4,function(x) i[x]<-test(100))

just to add some explantory stuff:

the difference between <- and <<- is that the first one is locally defined (i.e. within a function) and the second one is globally defined (i.e. within and outside of a function) and thus you can change the global variables and can work with some apply functions.