0

I am in a bit of a bind with an R function that I wrote which is producing the titular error, more specifically, "Number of items to replace is not a multiple of replacement length Error". It contains a helper function, "normative_value_lambda()", which works perfectly. I do not know how to modify it so as to eliminate the error.

Please any insights would be very much appreciated. I ran it on a Windows OS with this Example Dataset.

Code

    predicted_choices_lambda <- function()
    {
      predicted_lambda <- array(dim = c(100, 10))
      for(row in 1:100)
      {
        column <- 1
        idx <- 1
        lambda <- seq(0.5, 5, by = 0.5)
        while((column && idx) <= 10)
        {
          if(normative_value_lambda(row, lambda[idx]) > 0)
            predicted_lambda[row][column] <- TRUE
          else
            predicted_lambda[row][column] <- FALSE
          column <- column + 1
          idx <- idx + 1
        }
     }
      return (predicted_lambda)
    }

normative_value_lambda <- function(trial.index, lambda)
{
  win_percent <- as.numeric(gd$percent[gd$trial_index == trial.index])
  loss_percent <- 1 - win_percent

  win <- as.numeric(gd$gain[gd$trial_index == trial.index])
  lose <- as.numeric(gd$loss[gd$trial_index == trial.index])

  return ((win * win_percent) + (lambda * lose * loss_percent))
}
Sage Kase
  • 7
  • 3
  • 2
    Help others help you. Provide code for a minimal reproducible example and some data. We have no idea what `normative_value_lambda` does, so we can't run your predictive function. Read this too: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – John Polo Feb 23 '23 at 01:36
  • It's difficult to help without the complete code, but I note that the values of `column` and `idx` will always = 1 and never increment, because you assign the value 1 inside of the for-loop. – neilfws Feb 23 '23 at 01:39

1 Answers1

3

I think the error might be in the condition for your while loop. For example,

column = 5
idx = 11
(column && idx) <= 10

returns TRUE so sometimes you're looking for values of lambda that don't exist e.g. lambda[11] since the sequence is only of length 10. I think what you want is:

(column <= 10 && idx <= 10)
nrennie
  • 1,877
  • 1
  • 4
  • 14