Question

I would like to determine if a vector is either always increasing or always decreasing 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 would hope that the first two would return TRUE, and the last would return FALSE.

I tried a few 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 hoped that I could simply compare this vector with 1,2,3,4,5 and 5,4,3,2,1, but even that returns a string of logicals, rather than a single true or false:

> order(non)==c(1,2,3,4,5)
[1]  TRUE FALSE FALSE  TRUE FALSE
Was it helpful?

Solution

Maybe is.unsorted is the function your looking for

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

From the Description of is.unsorted you can find:

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

OTHER TIPS

Here's one way using ?is.unsorted:

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

Have a look at the additional arguments to is.unsorted, which can be passed here as well.

Here is one way without is.unsorted() to check if to vectors are sorted. This function will return true, if all elements in the vector given are sorted in an ascending manner or false if not:

is.sorted <- function(x) {
  if(all(sort(x, decreasing = FALSE) == x)) {
    return(TRUE)
  } else {
    return(FALSE)
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top