Reputation: 1012
In my example, I want to merge two vectors into a single sorted vector. For this purpose I have decided to use while-loop. Here is my code:
merge_sort_func <- function(vect1,vect2){
if((is.numeric(vect1) & is.numeric(vect2)) == FALSE){
stop("The argument must be numeric!")
}
new_vect <- c(vect1,vect2)
sort_vect <- numeric()
i <- length(unique(new_vect))
while(i != 0){
sort_vect <- c(sort_vect,new_vect[which(x == min(new_vect))])
new_vect <- new_vect[-which(x == min(new_vect))]
i <- i-1
}
sort_vect
}
But in my case it doesn't work:
In min(new_vect) : no non-missing arguments to min; returning Inf
I think, that the main problem in my code is connected with while
statement.
Can you tell me (or give me a hint) where am I wrong?
Upvotes: 1
Views: 65
Reputation: 22807
The code you posted didn't work (x
was undefined). I think this is what you want. Just a couple of small changes:|
merge_sort_func <- function(vect1, vect2) {
if ((is.numeric(vect1) & is.numeric(vect2)) == FALSE) {
stop("The argument must be numeric!")
}
new_vect <- c(vect1, vect2)
sort_vect <- numeric()
i <- length(unique(new_vect))
while (i != 0) {
x <- min(new_vect)
sort_vect <- c(sort_vect, new_vect[which(x == new_vect)])
new_vect <- new_vect[ - which(x == new_vect)]
i <- i - 1
}
sort_vect
}
Upvotes: 1