I need to calculate (in R) the number of positive and negative runs in a vector. For example, suppose I have a vector x
:
x = c(-23 , -2 , 5 , 8, 9, 12, -2, -1, 3, 5, 7)
than the number of runs is four, since I have: {-23,-2}, {5,8,9,12}, {-2,-1} and {3,5,7}. So basically every time the series changes sign, it counts as +1 in the run count.
Data Visualization using R Programming For example, if we have a vector x that contains some positive and some negative values and we want to find the number of values that are positive then we can use the command length(x[x>0]).
Use vector[vector>0] and vector[vector<0] to extract the positive and negative numbers, respectively.
If your vector is in x
, then length(rle(sign(x))$lengths)
will do.
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