r - Sorting a vector in R without using sort function
问题描述
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.
解决方案
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
推荐阅读
- perl - 如何在 ubuntu 下为 perl 安装 Filter::Crypto 模块
- ruby-on-rails - 调用实例方法时来自 &block 的未定义局部变量或方法
- c++ - Vulkan 初始化代码中出现奇怪的 C6385 警告
- flutter - 如何阻塞直到异步函数完成
- c# - 如何使用 C#8 IAsyncEnumerable
异步枚举任务并行运行 - c++ - 在 PCL 中使用 KinfuLS 包时出现的问题如何解决?
- java - 如何专门在firebase中获取用户数据
- karate - 空手道 API 如何捕获响应值以作为请求传递给另一个 API
- odoo - 如果订单行中的所有复选框都为真,则将复选框设置为真
- javascript - addEventListener 不会在 javascript 中触发