Reputation: 25
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.
Upvotes: 1
Views: 2170
Reputation: 174468
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.
Upvotes: 0