R:累积和,直到某个值

lvmkulzt  于 2022-12-25  发布在  其他
关注(0)|答案(2)|浏览(107)

我想计算在累计达到某个值之前要取多少个值。这是我的向量:第一个月
我从编写累积和函数开始:

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)
}

现在,有了极限

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)
}

不幸的是错误:

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
[...]
gcuhipw9

gcuhipw91#

你可以用cumsum来计算累积和,然后计算低于某个阈值n的值的数量:

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

f(myvec, 4)
#[1] 9

f(myvec, 1.1)
#[1] 5
1bqhqjot

1bqhqjot2#

可以在函数中放置一个while循环。如果达到限制,则停止进一步计算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

特别适用于较长的载体,例如

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

相关问题