Home > Software engineering >  How can I remove Error in if : missing value where TRUE/FALSE needed
How can I remove Error in if : missing value where TRUE/FALSE needed

Time:10-26

for (x in 1:length(s))
{
  if(s[x] == "1")
    {
    s=s[-x]
    }

}

The code runs and gives me the correct output however I still keep getting this error.

Is there something I am missing in the for loop?

CodePudding user response:

The issue is that your loop runs from 1 to length(s). However, inside your loop you are dropping elements, i.e. you reduce the length and sooner or latter you arrive at a situation where x > length(s) and hence s[x] = NA which results in the error:

set.seed(123)
s <- sample(c(1:2), 10, replace = TRUE)

for (x in 1:length(s)) {
  print(sprintf("length(s): %s, x: %s, , s[x]: %s", length(s), x, s[x]))
  if (s[x] == "1") {
    s <- s[-x]
  }
}
#> [1] "length(s): 10, x: 1, , s[x]: 1"
#> [1] "length(s): 9, x: 2, , s[x]: 1"
#> [1] "length(s): 8, x: 3, , s[x]: 1"
#> [1] "length(s): 7, x: 4, , s[x]: 2"
#> [1] "length(s): 7, x: 5, , s[x]: 2"
#> [1] "length(s): 7, x: 6, , s[x]: 1"
#> [1] "length(s): 6, x: 7, , s[x]: NA"
#> Error in if (s[x] == "1") {: missing value where TRUE/FALSE needed

One option to achieve your desired without a loop would be:

set.seed(123)
s <- sample(c(1:2), 10, replace = TRUE)

s[s != "1"]
#> [1] 2 2 2 2
  •  Tags:  
  • r
  • Related