2
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!

cmaher
  • 5,100
  • 1
  • 22
  • 34
R_learner
  • 39
  • 1
  • 4
  • 4
    The `RStudio` tag is for questions that involve the RStudio IDE per se, not general R questions (which is what this is). Also -- you really should post enough data for someone to be able to reproduce your problem. Please read [mcve]. – John Coleman Feb 15 '18 at 18:12
  • Second the request for sample data. Specifically, we don't know what `mom.wealth` or `dax.p` *look like*. Another quick reference for asking a *reproducible question* (very important to get a relevant answer) is https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example. – r2evans Feb 15 '18 at 18:41

2 Answers2

1

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))

MKR
  • 19,739
  • 4
  • 23
  • 33
0

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

karen
  • 822
  • 1
  • 6
  • 22