Check if the variable is in ascending order in R

Suppose I have a variable

x <- c(1,3,5,7,8) 

Now x is in ascending order

How to check if a variable is in ascending order in R?

+6
source share
3 answers

From ?is.unsorted :

Check if the object is sorted (in ascending order) ...

So in this case, you could:

 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 

This function is fast because it crosses the vector and breaks the loop as soon as the element is not "> =" (or ">" if "strictly = T") from the previous one.

+10
source

Try the following:

 all(diff(x) > 0) 

or

 all(diff(x) >= 0) 

I agree with @flodel that is.unsorted (h / t @alexis_laz) is probably even better.

+8
source

Look at the differences:

 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> 
+7
source

All Articles