for loop adding values with similar sign in a numeric vector in R -


create numeric vector x:

x <- c(1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, 1, -1) class(x) 

assign variable first value of x:

a <- x[1] 

iterate through x , add elements similar in sign a:

for(i in 2:length(x)) {        if (sign(x[i]) ==  sign(x[i-1]))            {a <- + x[i]}} 

somehow, a becomes 4 instead of 3! of why happening appreciated.

use rle function

x <- c(1, 1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, 1, -1) <- x[1]  out <- rle(x) with(out, lengths[values == a]) # [1] 3 1 2 1 1 2 2 2 

first change in sign:

a <- with(out, lengths[values == a])[1] # [1] 3 

if reverse signs:

x <- -x # [1] -1 -1 -1  1 -1  1  1 -1 -1  1 -1  1  1 -1  1  1 -1 -1  1 -1 -1  1 -1 -1  1  <- x[1]  out <- rle(x) <- with(out, lengths[values == a])[1] # [1] 3 

Comments

Popular posts from this blog

matlab - error with cyclic autocorrelation function -

django - (fields.E300) Field defines a relation with model 'AbstractEmailUser' which is either not installed, or is abstract -

c# - What is a good .Net RefEdit control to use with ExcelDna? -