简体   繁体   English

R:累积和直到某个值

[英]R: cumulative sum until certain value

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)这是我的向量: 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
[...]

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 :您可以使用cumsum计算累积和,然后计算低于特定阈值n的值的数量:

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

f(myvec, 4)
#[1] 9

f(myvec, 1.1)
#[1] 5

You can put a while loop in a function.您可以在函数中放置一个while循环。 This stops further calculation of the cumsum if the limit is reached.如果达到限制,这将停止进一步计算cumsum

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, eg对于较长的向量特别有用,例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM