英文:
How to sort data by using loops?
问题
我想编写一个函数,可以按升序或降序重新排列一个向量。我知道可以使用sort和order函数来实现,但我想手动完成。
英文:
I want to write a function that rearranges a vector in ascending or descending order. I know I can use sort and order functions but I want to do it manually.
答案1
得分: 1
如果您想练习编写自己的排序函数,这里有一个应用了递归方法的示例:
mysort <- function(v, descending = FALSE) {
if (length(v) == 1) return(v)
if (descending) return(c(max(v), mysort(v[-which.max(v)], descending = descending)))
return(c(min(v), mysort(v[-which.min(v)])))
}
示例
v <- c(1, 2, 5, 4, 2, 7)
# 升序方式
mysort(v)
# 降序方式
mysort(v, descending = TRUE)
这样会得到以下结果:
> mysort(v)
[1] 1 2 2 4 5 7
> mysort(v, descending = TRUE)
[1] 7 5 4 2 2 1
英文:
If you want to practice writing your own sorting function, here is a example which applies a recursion approach:
mysort <- function(v, descending = F) {
if (length(v)==1) return(v)
if (descending) return(c(max(v),mysort(v[-which.max(v)],descending = descending)))
return(c(min(v),mysort(v[-which.min(v)])))
}
EXAMPLE
v <- c(1,2,5,4,2,7)
# ascending manner
mysort(v)
# descending manner
mysort(v,descending = T)
such that
> mysort(v)
[1] 1 2 2 4 5 7
> mysort(v,descending = T)
[1] 7 5 4 2 2 1
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论