检查变量在R中是否按递增顺序排列

检查变量在R中是否按递增顺序排列,r,sorting,R,Sorting,假设我有一个变量 x <- c(1,3,5,7,8) x试试这个: all(diff(x) > 0) 或 我同意@flodel所说的是。未分类的(h/t@alexis_laz)可能更好。看看区别: R> x <- c(1,3,5,7,8) R> allIncreasing <- function(x) all(diff(x)>0) R> allIncreasing(x) [1] TRUE R> y <- x; y[3] <-

假设我有一个变量

x <- c(1,3,5,7,8)
x试试这个:

all(diff(x) > 0)


我同意@flodel所说的
是。未分类的
(h/t@alexis_laz)可能更好。

看看区别:

R> x <- c(1,3,5,7,8) 
R> allIncreasing <- function(x) all(diff(x)>0)
R> allIncreasing(x)
[1] TRUE
R> y <- x; y[3] <-0 
R> allIncreasing(y)
[1] FALSE
R> 
R>x所有增加0)
R> 全部递增(x)
[1] 真的
R> y

中的是未排序的

测试对象是否未排序(按递增顺序)

因此,在这种情况下,您可以:

is.sorted = Negate(is.unsorted)
is.sorted(x)
#[1] TRUE
#> is.sorted(1:5)
#[1] TRUE
#> is.sorted(5:1)
#[1] FALSE
#> is.sorted(sample(5))
#[1] FALSE
#> is.sorted(sort(runif(5)))
#[1] TRUE
#> is.sorted(c(1,2,2,3))
#[1] TRUE
#> is.sorted(c(1,2,2,3), strictly = T)
#[1] FALSE

这个函数速度很快,因为它在向量上循环,只要元素不是上一个元素的“>=”(或者“>”,如果“严格地=T”),它就会中断循环。

也许,否定
是。未排序的
在这里工作?+1-你也可以
全部(尾(x,-1)>头(x,-1))
。它更容易打字,但速度更快,因为它避免了计算差异。
is.sorted = Negate(is.unsorted)
is.sorted(x)
#[1] TRUE
#> is.sorted(1:5)
#[1] TRUE
#> is.sorted(5:1)
#[1] FALSE
#> is.sorted(sample(5))
#[1] FALSE
#> is.sorted(sort(runif(5)))
#[1] TRUE
#> is.sorted(c(1,2,2,3))
#[1] TRUE
#> is.sorted(c(1,2,2,3), strictly = T)
#[1] FALSE