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
Post a Comment