[英]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? 我想知道在基数R中是否有一种方法可以测试两个向量(两者)是增加还是减少?
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
和b
时测试应返回FALSE
(请参见下文),而测试c
和d
时测试应返回TRUE
(请参见下文)。
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. 为了清楚起见,我要问任意两个向量 (当都排序但不考虑它们的长度时)是否在减小 (例如10:0
100:97
, -8:-10
),则测试应返回TRUE,否则返回两个向量都再次增加,测试应返回TRUE,否则应返回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". 根据@parvin的说法,“增加”的定义只是“具有增加的趋势”。 So I suggest that instead of using diff
, we use lm
. 因此,我建议不要使用diff
,而要使用lm
。
Say I have two numeric vector, x
and y
, here is my solution: 说我有两个数值向量x
和y
,这是我的解决方案:
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 |
xor
完全满足了需求,因此我们可以摆脱使用|
组合两个语句的麻烦|
or ||
或||
. 。 unname
is used to simply delete the coefficient name. unname
用于简单地删除系数名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.