R_learner
R_learner

Reputation: 39

Problems with loop in R

mom.wealth <- matrix(NA,nrow(dax.p),1)

mom.wealth[13,1]=1

mom.stocks <- matrix(NA,nrow(dax.p),ncol(dax.p))

for (row in 13:nrow(dax.p)-1) {
   for (column in 2:ncol(dax.p)) {
     mom.stocks[row,column] <- mom.wealth[row,1]*mom.weight[row,column]/dax.p[row,column]
  }

   mom.wealth[row+1,1] <- sum(mom.stocks[row,-1]*dax.p[row+1,-1])
} 

There is something wrong with the last line here. It does not come any error message, but all results are just NA.

Thank you in advance!

Upvotes: 2

Views: 57

Answers (2)

MKR
MKR

Reputation: 20085

The root-case of the problem is for (row in 13:nrow(dax.p)-1) line.

You can try this simple code to understand the problem.

for (row in 13:16-1) {
  print(row) 
}

The above code will print like
[1] 12
[1] 13
[1] 14
[1] 15

That means 1 is subtracted from both 13 and 16 before checking fro in condition.

Now, in your case the actual value is at 13th row of mom.wealth but your loop starts from 12th row. The 12th row has NA value. Hence, subsequent rows will get NA.

The fix is: Change the line for (row in 13:nrow(dax.p)-1) with for (row in 13:(nrow(dax.p)-1))

Upvotes: 1

karen
karen

Reputation: 812

Try:

mom.wealth <- matrix(NA,nrow(dax.p),1)

mom.wealth[13,1]=1

mom.stocks <- matrix(NA,nrow(dax.p),ncol(dax.p))

for (row in 13:nrow(dax.p)-1) {


for (column in 2:ncol(dax.p)) {


mom.stocks[row,column] <- mom.wealth[row,1]*mom.weight[row,column]/dax.p[row,column] }

mom.wealth[row+1,1] <- sum(mom.stocks[row,-1]*dax.p[row+1,-1], na.rm = T) } 

If it does not work I need dataset to understand the problem...

Upvotes: 0

Related Questions