简体   繁体   中英

Error ... missing value where TRUE/FALSE needed

I've been trying to write a code to sort a vector in R, but I keep getting this error message: Error in if (data[j] < data[k]) { : missing value where TRUE/FALSE needed

This is my sort function so far:

sortscore <- function(data){
   new <- 0
   x <- data
  
   for (i in 1:length(data)){
      new[i] <- minscore(x)
      x <- x[x!=minscore(x)]
      x
   }
   new
}

This is the minscore function:

minscore <- function(data){
  j <- 1;k <- j+1; min <- 0
  repeat {
    if(data[j]<data[k]){
      min <- data[j]
      k <- k+1
    }
    else{
      min <- data[k]
      j <- k
      k <- k+1
    }
    if(k==length(data)+1) break
  }
  return(min)
}

I can only use length() function for a built-in function, hence the need for a sort function. Please help me understand.

The problem is that your sortscore function shrinks x by one on every iteration, meaning that on the final iteration, it only contains a single number. You are therefore calling the minscore function on a single number.

The test if(data[j]<data[k]) inside minscore needs at least two numbers to work or else it will throw an error, since k is always 1 higher than j . data[2] doesn't exist if data is length 1.

The simple solution is that if data is length 1, the minscore function returns it unchanged.

So, if we change your function to:

minscore <- function(data){
  
  if(length(data) == 1) return(data)
  
  j <- 1;k <- j+1; min <- 0
  repeat {
    if(data[j]<data[k]){
      min <- data[j]
      k <- k+1
    }
    else{
      min <- data[k]
      j <- k
      k <- k+1
    }
    if(k==length(data)+1) break
  }
  return(min)
}

Then we should get a working sort function:

x <- sample(20)
x
#> [1]  8 14 11 19 20  2  3 10  1 15  4 17  6 16  7  5 13 12 18  9

sortscore(x)
#> [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20

Nice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM