Home > Mobile >  R: cumulative sum until certain value
R: cumulative sum until certain value

Time:12-24

I want to calculate how many values are taken until the cumulative reaches a certain value. This is my vector: myvec = seq(0,1,0.1)

I started with coding the cumulative sum function:

cumsum_for <- function(x)
{
  y = 1
  for(i in 2:length(x))  # pardon the case where x is of length 1 or 0
    {x[i] = x[i-1]   x[i]
    y = y 1}
  return(y)
}

Now, with the limit

cumsum_for <- function(x, limit)
{
  y = 1
  for(i in 2:length(x))  # pardon the case where x is of length 1 or 0
    {x[i] = x[i-1]   x[i]
    if(x >= limit) break
    y = y 1}
  return(y)
}

which unfortunately errors:

myvec = seq(0,1,0.1)
cumsum_for(myvec, 0.9)
[1] 10
Warning messages:
1: In if (x >= limit) break :
  the condition has length > 1 and only the first element will be used
[...]

CodePudding user response:

What about this? You can use cumsum to compute the cumulative sum, and then count the number of values that are below a certain threshold n:

f <- function(x, n) sum(cumsum(x) <= n)

f(myvec, 4)
#[1] 9

f(myvec, 1.1)
#[1] 5

CodePudding user response:

You can put a while loop in a function. This stops further calculation of the cumsum if the limit is reached.

cslim <- function(v, l) {
  s <- 0
  i <- 0L
  while (s < l) {
    i <- i   1
    s <- sum(v[1:i])
  }
  i - 1
}

cslim(v, .9)
# [1] 4

Especially useful for longer vectors, e.g.

v <- seq(0, 3e7, 0.1)
  • Related