Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the number of positive and negative runs in a vector

Tags:

r

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.

like image 619
jeremy.staub Avatar asked Jun 22 '12 08:06

jeremy.staub


People also ask

How do you find the positive value of a vector?

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]).

How do you separate positive and negative numbers in R?

Use vector[vector>0] and vector[vector<0] to extract the positive and negative numbers, respectively.


1 Answers

If your vector is in x, then length(rle(sign(x))$lengths) will do.

like image 54
danas.zuokas Avatar answered Nov 15 '22 14:11

danas.zuokas