Search notes:

R function: cumsum

cumsum(vec) returns a vector that contains the cumulative sum for each element in vec:
a1 <- c(2, 3, 1, -4, 2)
cumsum(a1)
#
#  2 5 6 2 4
Github repository about-r, path: /functions/cumsum/cumsum.R

Creating test data

cumsum combined with rnorm allows to quickly create test data that look like developing figures:
#
#  https://stackoverflow.com/a/4877936/180275
#
library(ggplot2 )
require(reshape2)

set.seed(2808);

nofObs <- 15;

test.data <- data.frame(
    x     = 1:nofObs             ,
    val_1 = cumsum(rnorm(nofObs)),
    val_2 = cumsum(rnorm(nofObs)),
    val_3 = cumsum(rnorm(nofObs))
)

#
#  melt data frame so that it looks something like
#
#     x    dat       value
#     --------------------
#     1  val_1   1.9203381
#     2  val_1   1.5782440
#     3  val_1   0.5306273
#     …        
#     1  val_2  -0.9640162
#     …
#
test.data.narrow <- melt(
    test.data          ,
    id.vars       = 'x',
    variable.name = 'dat'
)

ggplot(
    test.data.narrow,
    aes(
        x = x,
        y = value)
) +
geom_line(
       aes(colour = dat)
)
Github repository about-r, path: /functions/cumsum/create-test-data.R
See also ggplot2.

See also

sum(), cummax()
Index to (some) R functions

Index