简体   繁体   中英

Testing whether two vectors are increasing or decreasing in R

I was wondering if there might be a way in base R to test whether two vectors (BOTH OF THEM) are increasing or decreasing?

For example, the test should return FALSE when testing a and b (see below) and the test should return TRUE when testing c and d (see below).

a = 5:10
b = 10:5
c = seq(-5, 15)
d = seq(-15, -8)

For clarity, I'm asking any two vectors (when both ordered but regardless of their length) if are decreasing (eg, 10:0 , 100:97 , -8:-10 ) then the test should return TRUE, else if the two vectors are both increasing again the test should return TRUE, else should return FALSE.

"Both vectors increasing" would be

all(diff(x)>0) && all(diff(y)>0)

"Both vectors decreasing" would be

all(diff(x)<0) && all(diff(y)<0)

You could combine these with || (or).

According to @parvin, the definition of "increasing" is just "having an increasing trend". So I suggest that instead of using diff , we use lm .

Say I have two numeric vector, x and y , here is my solution:

unname(!xor(lm(x ~ seq_along(x))$coefficient[2] > 0, lm(y ~ seq_along(y))$coefficient[2] > 0))

xor fulfills exactly the need so we can get rid of combining two statements with | or || . unname is used to simply delete the coefficient name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM