1

I am new to R and really need some help. I keep getting the error message

"Error in eff_weights[i, ] <- eff.port$pw : number of items to replace is not a multiple of replacement length"

when I run the loop. Can someone help me figure out what I am doing wrong. Thank you so much in advance!

 # Create for loop to find efficient frontier

for (i in 1 : length(grid)) {
   eff.port <- portfolio.optim(returns, pm = grid[i], shorts =TRUE)
   vector_pm[i] <- eff.port$pm
   vector_psd[i] <- eff.port$ps
   eff_weights[i, ] <- eff.port$pw
}
rg255
  • 4,119
  • 3
  • 22
  • 40
Lauren
  • 65
  • 6
  • Please, try to create a reproducible example: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – DzimitryM Apr 03 '20 at 21:01

1 Answers1

0

Without a sample of your data or dummy data to reproduce the problem it is hard to provide a certain solution. However, in your loop you assign a vector of values from a column, eff.port$pw, to the ith row of a dataframe or matrix, eff_weights[i, ]. The error message is saying the are different lengths - use the length() or dim() functions to compare the lengths of these two. Your vector eff.port$pw and row eff_weight[i,] must be the same length.

rg255
  • 4,119
  • 3
  • 22
  • 40
  • Thank you so much for looking at this. This is what I am gerneating for eff_port$pw [1] 2.2342660 -0.2146492 -0.1278270 0.2958349 -0.9179933 -0.3243578 -0.2562219 [8] 0.3109482 – Lauren Apr 04 '20 at 00:48
  • Could you do `dim(eff_port$pw)` and `dim(eff_weight[1,])` and post the results as a comment here please – rg255 Apr 04 '20 at 04:04
  • For dim(eff_weight[1, ]) Error: object 'eff_weight' not found. I have the following assigned to eff_weight. eff_weights <- matrix(NA, 60, 30) – Lauren Apr 04 '20 at 15:33
  • I was able to get it to work! I just needed to change the 30 to an 8 and it ran perfect. thank you for your help! – Lauren Apr 04 '20 at 15:47
  • As it solved your problem you should accept the answer – rg255 Apr 04 '20 at 20:30