error, "missing value where TRUE/FALSE needed" in while look

I'm using while within a for loop

r0 <- 2.5
f <- seq(from = 1, to = 0, by = -0.001)
fes_eq <- numeric(length(f))
n <- length(f)
for (i in 1:n)
{
  fes_eq[i] <- 1-f-exp(-r0*f[i])
  while (fes_eq[i] < 0)
  {
    print(f[i])
    i <- i+1
  }
}

r outputs all values of f and presents the warning "Error in while (fes_eq[i] < 0) { : missing value where TRUE/FALSE needed" at the end
i am trying to get all values of f that gives negative values of fes_eq and I expect to see the smallest f to be around 0.892.
what goes wrong here? what should I do to fix it?

The while loop if it activates for any negative value will spin off I ever higher beyond where fes_eq[i] could have been assigned. So the values will be missing. And a missing value is not true or false so while loop condition will error

1 Like

I see. How can I change it to make it work? (thank you!!)

Replace all of

while (fes_eq[i] < 0)
  {
    print(f[i])
    i <- i+1
  }

With

if(fes_eq[i] < 0)
print(f[i])

sidenote, I don't understand the actual conceptual purpose of your code, but as written it throws warnings, and it doesn't make intuitive sense why one would do the thing that gives the warnings.
Therefore I suspect that

fes_eq[i] <- 1-f-exp(-r0*f[i])

should be changed to

fes_eq[i] <- 1-f[i]-exp(-r0*f[i])

so that each fes_eq[i] value equals exactly one thing, and not 1001 things...
but I don't know

this solves the problem, thank you so much

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.