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

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

World Changing Mathematical Discoveries

Value at Risk xls

Random posts:

Quantitative Finance Collector PDF

Floating Strike Lookback Option

Free Mini Email Trading Course

CVA and Wrong-Way Risk

SOCR of UCLA

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.