Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if a vector is ordered

Tags:

sorting

r

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
like image 599
user3603093 Avatar asked May 08 '14 16:05

user3603093


People also ask

Is a vector ordered?

No vector is by definition guaranteed to be sorted, so elements won't be "in order". Moreover, all iterators and references to elements of a vector will be invalidated upon insertion only if reallocation occurs (i.e. when the size of the vector exceeds its capacity).

How do I know if my data is ordered in R?

Check if a Factor is an Ordered Factor in R Programming – is. ordered() Function. is. ordered() function in R Programming Language is used to check if the passed factor is an ordered factor.

Is sorted in R?

unsorted() function in R Language is used to check if an object is sorted or not. It returns False if the object is sorted otherwise True. Here, the output is FALSE for vector because it is sorted and matrix is unsorted, hence the function returns TRUE for matrix.

How do I order a vector in R?

To sort a vector in R programming, call sort() function and pass the vector as argument to this function. sort() function returns the sorted vector in increasing order. The default sorting order is increasing order. We may sort in decreasing order using rev() function on the output returned by sort().


1 Answers

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.

like image 121
Jilber Urbina Avatar answered Sep 30 '22 16:09

Jilber Urbina