r - 确定向量是否有序

标签 r sorting

我想确定一个向量在 R 中是总是增加还是总是减少。

理想情况下,如果我有这三个向量:

asc=c(1,2,3,4,5)
des=c(5,4,3,2,1)
non=c(1,3,5,4,2)

我希望前两个返回 TRUE,最后一个返回 FALSE。

我尝试了几种方法。首先,我试过:
> is.ordered(asc)
[1] FALSE
> is.ordered(des)
[1] FALSE
> is.ordered(non)
[1] FALSE

我也试过:
> order(non)
[1] 1 5 2 4 3

并希望我可以简单地将这个向量与 1,2,3,4,5 进行比较和 5,4,3,2,1 ,但即使这样也返回一串逻辑,而不是单个真或假:
> order(non)==c(1,2,3,4,5)
[1]  TRUE FALSE FALSE  TRUE FALSE

最佳答案

也许 is.unsorted 是您要找的功能

> is.unsorted(asc)
[1] FALSE
> is.unsorted(rev(des)) # here you need 'rev'
[1] FALSE
> is.unsorted(non)
[1] TRUE

来自 is.unsorted 的描述你可以找到:

Test if an object is not sorted (in increasing order), without the cost of sorting it.

关于r - 确定向量是否有序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23547929/

相关文章:

algorithm - mergesort合并步骤的时间复杂度是多少?

arrays - 获取数组排序的索引

linux - 在Linux shell脚本中对多列进行排序

java - 如何有效地对一个数组进行排序

r - 从 R 中的字符串中提取字母

r - 错误: unused arguments in Shiny (R)

r - 将向量列表列表转换为 R 中的数据框

r - 为什么data.table定义为:= rather than overloading <-?

javascript - R Shiny : conditionalPanel sharing sidebars on select panels

arrays - 如何在 Swift 中对 NSDate 进行排序