假设我有一个变量
x <- c(1,3,5,7,8)
Run Code Online (Sandbox Code Playgroud)
现在x
正在增加秩序
如何检查变量是否在R中递增?
ale*_*laz 12
来自?is.unsorted
:
测试对象是否未排序(按递增顺序)...
所以,在这种情况下,您可以:
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
Run Code Online (Sandbox Code Playgroud)
这个函数很快,因为它会循环遍历向量,并且只要元素不是前一个元素的"> ="(或">",如果是"strict = T")就会中断循环.
试试这个:
all(diff(x) > 0)
Run Code Online (Sandbox Code Playgroud)
要么
all(diff(x) >= 0)
Run Code Online (Sandbox Code Playgroud)
我同意@flodel is.unsorted
(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>
Run Code Online (Sandbox Code Playgroud)