0

This is a reproducible example:

I want to see if tac2 is less than 80% tac and if it is, then cap the decrease at 80% of tac.

Error in if ((tac2[i] - tac) < tac * 0.8) { : missing value where TRUE/FALSE needed_

tac = 1000 
tac2= c(790,600,678,900,1200,300,800,9000) 

 R
for (i in tac2) {
  if ((tac2[i]-tac) < tac*.8) {
  tac2[i] <- tac - tac*.2 
} else {
  tac2[i] = tac2[i]
  print(tac2)
} 
} 
J_S_Moss
  • 21
  • 4
  • Please do research before asking questions. If you had searched [`[r] missing value where TRUE/FALSE `](https://stackoverflow.com/search?tab=votes&q=%5br%5d%20missing%20value%20where%20TRUE%2fFALSE%20) (the literal text from your error and your title here), you will find many questions and answers that address this problem. – r2evans Apr 02 '20 at 17:57

1 Answers1

0

It looks like the problem is in for (i in tac2). Your i's are going to be the values in tac2, so on the first iteration of the loop, i is 790. You're getting an error because tac2[790] doesn't exist.

Instead, try for (i in 1:length(tac2)). That'll loop over the numbers 1 through however long tac2 is.

Lynn L
  • 523
  • 3
  • 7
  • Better than `1:length(...)` is `seq_len(length(...))` or `seq_along(...)`. The difference is in the event that the vector/list is of length 0. Intuition suggests that the `for` loop should do nothing when length 0, but notice the difference between `1:length(list())` and `seq_along(list())`; in the latter, the loop will do nothing; in the former, it will loop twice (and likely fail trying to do so). – r2evans Apr 02 '20 at 17:58
  • Okay thanks a lot guys :) – J_S_Moss Apr 03 '20 at 06:31