Quantcast
Viewing all articles
Browse latest Browse all 15

Answer by Allan Cameron for Count and summation of positive and negative number sequences

Here's a simple non-looping function in R:

count_and_sum <- function(x){  runs   <- rle((x > 0) * 1)$lengths  groups <- split(x, rep(1:length(runs), runs))  output <- function(group) data.frame(x = group, n = seq_along(group), sum = cumsum(group))  result <- as.data.frame(do.call(rbind, lapply(groups, output)))  `rownames<-`(result, 1:nrow(result))}

So you can do:

set.seed(100)x <- round(rnorm(20, sd = 0.02), 3)count_and_sum(x)#>         x n    sum#> 1  -0.010 1 -0.010#> 2   0.003 1  0.003#> 3  -0.002 1 -0.002#> 4   0.018 1  0.018#> 5   0.002 2  0.020#> 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.010 1  0.010#> 19 -0.018 1 -0.018#> 20  0.046 1  0.046

Created on 2020-02-16 by the reprex package (v0.3.0)


Viewing all articles
Browse latest Browse all 15

Trending Articles



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