I want to write a code to count and sum any positive and negative series of numbers.
Numbers are either positive or negative(no zero).
I have written codes with for
loops. Is there any creative alternative?
Data
R
set.seed(100)x <- round(rnorm(20, sd = 0.02), 3)
python
x = [-0.01, 0.003, -0.002, 0.018, 0.002, 0.006, -0.012, 0.014, -0.017, -0.007, 0.002, 0.002, -0.004, 0.015, 0.002, -0.001, -0.008, 0.01, -0.018, 0.046]
loops
R
sign_indicator <- ifelse(x > 0, 1,-1)number_of_sequence <- rep(NA, 20)n <- 1for (i in 2:20) { if (sign_indicator[i] == sign_indicator[i - 1]) { n <- n + 1 } else{ n <- 1 } number_of_sequence[i] <- n}number_of_sequence[1] <- 1#############################summation <- rep(NA, 20)for (i in 1:20) { summation[i] <- sum(x[i:(i + 1 - number_of_sequence[i])])}
python
sign_indicator = [1 if i > 0 else -1 for i in X]number_of_sequence = [1]N = 1for i in range(1, len(sign_indicator)): if sign_indicator[i] == sign_indicator[i - 1]: N += 1 else: N = 1 number_of_sequence.append(N)#############################summation = []for i in range(len(X)): if number_of_sequence[i] == 1: summation.append(X[i]) else: summation.append(sum(X[(i + 1 - number_of_sequence[i]):(i + 1)]))
result
x n_of_sequence sum1 -0.010 1 -0.0102 0.003 1 0.0033 -0.002 1 -0.0024 0.018 1 0.0185 0.002 2 0.0206 0.006 3 0.0267 -0.012 1 -0.0128 0.014 1 0.0149 -0.017 1 -0.01710 -0.007 2 -0.02411 0.002 1 0.00212 0.002 2 0.00413 -0.004 1 -0.00414 0.015 1 0.01515 0.002 2 0.01716 -0.001 1 -0.00117 -0.008 2 -0.00918 0.010 1 0.01019 -0.018 1 -0.01820 0.046 1 0.046