Determine if a vector is ordered

I would like to determine if a vector always increases or always decreases in R.

Ideally, if I had these three vectors:

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

I hope the first two will return TRUE, and the last will return FALSE.

I tried several approaches. First I tried:

 > is.ordered(asc) [1] FALSE > is.ordered(des) [1] FALSE > is.ordered(non) [1] FALSE 

And I also tried:

 > order(non) [1] 1 5 2 4 3 

And I hoped that I could just compare this vector with 1,2,3,4,5 and 5,4,3,2,1 , but even this returns a line of logic, and not a single truth or falsehood:

 > order(non)==c(1,2,3,4,5) [1] TRUE FALSE FALSE TRUE FALSE 
+9
sorting r order
source share
3 answers

Maybe is.unsorted is the function you are looking for

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

In the is.unsorted description you can find:

Check if the object is sorted (in ascending order) without the cost of sorting it.

+11
source share

Here is one way ?is.unsorted :

 is.sorted <- function(x, ...) { !is.unsorted(x, ...) | !is.unsorted(rev(x), ...) } 

See the additional arguments to is.unsorted , which can also be passed here.

+5
source share

is.ordered applies to factor variables, i.e. must be an ordered factor to return TRUE

 > asc <- factor(1:5, ordered = TRUE) > is.ordered(asc) ## [1] TRUE ## -------- > des <- 5:1 ## numeric vector > des2 <- as.ordered(des) ## converts to ordered factor > is.ordered(des2) ## [1] TRUE 

To compare them,

 > levels(des2) %in% levels(asc) ## [1] TRUE TRUE TRUE TRUE TRUE 
0
source share

All Articles