Vector of Cumulative Sums in R

How to calculate cumulative sum?

# replace the second column for the cumsum of the initial second column
data[, 2] <- cumsum(data[, 2])

Vector of cumulative sums in R

Please correct me if I'm misunderstanding, but I believe you simply want this:

I <- cumsum(sqrt(1 - U^2))

It is unclear why you want to use for loops.

Cumulative sums in R

Try outer

> sum(outer(1:10, 1:5, FUN = function(i,j) i^5/(10+j^i)))
[1] 20845.76

Using tapply and cumsum function for multiple vectors in R

if there are more than one group, wrap it in a list, but note that tapply in a summarising function and it can split up when we specify function like cumsum.

 tapply(date_country$n, list(date_country$country, date_country$pangolin_lineage), cumsum))

But, this is much more easier with ave i.e. if we want to create a new column, avoid the hassle of unlist etc. by just using ave

ave(date_country$n, date_country$country, 
date_country$pangolin_lineage, FUN = cumsum)
#[1] 1 2 3 1 4 1

Cumulative sum in R by group and start over when sum of values in group larger than maximum value

One purrr approach could be:

cumsum(c(FALSE, diff(accumulate(test, ~ ifelse(.x >= 10, .y, .x + .y))) <= 0))

[1] 0 0 1 1 1 2 2 2 3

R: Cumulative sum if difference over threshold

I would do this with a logical index used for subsetting. It should be true for all elements of x that shall be "cumsumed" and false for the rest.

idx <- x >= day_vec

Now you can use it to compute the cumsum and assign it to the correct elements in x:

x[idx] <- cumsum(x[idx])
x
#[1] 0 0 31 61 0 15 16

How to cumsum the elements of a vector under certain condition in R?

A base R option with Reduce

> Reduce(function(x, y) ifelse(x * y > 0, x + y, y), vector_A, accumulate = TRUE)
[1] 1 2 -1 -2 -3 1 -1 -2 1 -1

or using ave + cumsum

> ave(vector_A, cumsum(c(1, diff(sign(vector_A)) != 0)), FUN = cumsum)
[1] 1 2 -1 -2 -3 1 -1 -2 1 -1


Related Topics



Leave a reply



Submit