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?
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.
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.
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.
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().
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With