Quantcast
Viewing all articles
Browse latest Browse all 15

Answer by MKa for Count and summation of positive and negative number sequences

In R, you could also do:

# DATAset.seed(100)x <- round(rnorm(20, sd = 0.02), 3)library(data.table)dt <- data.table(x = x)# Create Positive or Negative variabledt$x_logical <- ifelse(dt$x > 0, "P", "N")# Create a reference data.frame/table to keep continuous countsseq_dt <- data.frame(val = rle(x = dt$x_logical)$lengths)seq_dt$id <- 1:nrow(seq_dt)# Map id in the main data.table and get cumulative sumdt$id <- rep(seq_dt$id, seq_dt$val)dt[, csum := cumsum(x), by = "id"]        x x_logical id   csum 1: -0.010         N  1 -0.010 2:  0.003         P  2  0.003 3: -0.002         N  3 -0.002 4:  0.018         P  4  0.018 5:  0.002         P  4  0.020 6:  0.006         P  4  0.026 7: -0.012         N  5 -0.012 8:  0.014         P  6  0.014 9: -0.017         N  7 -0.01710: -0.007         N  7 -0.02411:  0.002         P  8  0.00212:  0.002         P  8  0.00413: -0.004         N  9 -0.00414:  0.015         P 10  0.01515:  0.002         P 10  0.01716: -0.001         N 11 -0.00117: -0.008         N 11 -0.00918:  0.010         P 12  0.01019: -0.018         N 13 -0.01820:  0.046         P 14  0.046

Viewing all articles
Browse latest Browse all 15

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>