Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check whether a variable is in increasing order in R

Tags:

sorting

r

Supposing I have a variable

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

Now x is in increasing order

How to check whether a variable is in increasing order in R?

like image 714
user3171906 Avatar asked Apr 02 '14 20:04

user3171906


People also ask

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.

How do I sort by increasing order in R?

To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.

What is the order of variable in R?

order() in R Below the code contains variable x , which includes a vector with a list of numbers. The numbers are ordered according to its index by using order(x) . Here the order() will sort the given numbers according to its index in the ascending order.

How do you sort a vector in ascending order 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().


3 Answers

From ?is.unsorted:

Test if an object is not sorted (in increasing 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 loops over the vector and breaks the loop as soon as an element is not ">=" (or ">", if "strictly = T") from the previous one.

like image 149
alexis_laz Avatar answered Oct 23 '22 18:10

alexis_laz


Try this:

all(diff(x) > 0)

or

all(diff(x) >= 0)

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

like image 27
joran Avatar answered Oct 23 '22 19:10

joran


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> 
like image 20
Dirk Eddelbuettel Avatar answered Oct 23 '22 18:10

Dirk Eddelbuettel