Reputation: 11584
I am trying to write a function to sort a vector, but without using R's inbuilt 'Sort' function. My Code:
sorting <- function(x){
for(i in 1:length(x)){
for(j in (i+1):length(x)){
if(x[i] > x[j]){
x[c(i,j)] = x[c(j,i)]
}
}
}
x
}
I get below output:
> x <- c(3,1,4,7,2,9)
> sorting(x)
Error in if (x[i] > x[j]) { : missing value where TRUE/FALSE needed
>
I understand that we'll get above error when the 'IF' condition returns 'NA' instead of TRUE/FALSE.
Is there an issue with the statement:
for(j in (i+1):length(x)){
Python code for same:
def sorting(a):
for i in range(len(a)):
for j in range(i+1,len(a)):
if a[i] > a[j]:
a[i],a[j] = a[j],a[i]
return a
Output:
sorting([3,1,4,7,2,9])
Out[380]: [1, 2, 3, 4, 7, 9]
In Python, the code works fine.
Could someone let me know the issue with my R code.
Upvotes: 1
Views: 3198
Reputation: 8364
The problem is with that (i+1)
. When length(x)
reaches its max value, j
goes out of range. I added this: (length(x)-1)
.
sorting <- function(x){
for(i in 1:(length(x)-1)){
for(j in (i+1):length(x)){
if(x[i] > x[j]){
x[c(i,j)] = x[c(j,i)] # +1 for this
}
}
}
x
}
sorting(c(3,1,4,7,2,9))
[1] 1 2 3 4 7 9
Upvotes: 6
Reputation: 356
Sorting <- function(x){
xs <- rep(0, length(x))
for(i in 1:length(x)){
xs[i] = min(x)
x <- x[x != min(x)]
}
xs
}
Sorting(c(3,1,4,7,2,9))
[1] 1 2 3 4 7 9
Sorting is a function with a numeric vector argument x
. Initially xs
, the sorted vector of the same length as x
, is filled with zeroes. The for loop aims at assigning the minimum value of vector x
to each component of xs
(for(i in 1:length(x)){ xs[i] = min(x) )
. We then remove such minimum value from x by x <- x[x != min(x)] }
to find the next minimum value. Finally, xs
shows the sorted vector of x
.
Upvotes: 1