Quantcast
Channel: Count and summation of positive and negative number sequences - Stack Overflow
Viewing all articles
Browse latest Browse all 15

Answer by Andrew Gustar for Count and summation of positive and negative number sequences

$
0
0

Here is a simple tidyverse solution...

library(tidyverse) #or just dplyr and tidyrset.seed(100)x <- round(rnorm(20, sd = 0.02), 3)df <- tibble(x = x) %>%   mutate(seqno = cumsum(c(1, diff(sign(x)) != 0))) %>% #identify sequence ids  group_by(seqno) %>%                                  #group by sequences  mutate(n_of_sequence = row_number(),                 #count row numbers for each group         sum = cumsum(x)) %>%                          #cumulative sum for each group  ungroup() %>%   select(-seqno)                                       #remove sequence iddf# A tibble: 20 x 3        x n_of_sequence     sum<dbl>         <int>   <dbl> 1 -0.01              1 -0.01   2  0.003             1  0.003  3 -0.002             1 -0.002  4  0.018             1  0.018  5  0.002             2  0.0200 6  0.006             3  0.026  7 -0.012             1 -0.012  8  0.014             1  0.014  9 -0.017             1 -0.017 10 -0.007             2 -0.024 11  0.002             1  0.002 12  0.002             2  0.004 13 -0.004             1 -0.004 14  0.015             1  0.015 15  0.002             2  0.017 16 -0.001             1 -0.001 17 -0.008             2 -0.009 18  0.01              1  0.01  19 -0.018             1 -0.018 20  0.046             1  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>