我想计算在累计达到某个值之前要取多少个值。这是我的向量:第一个月
我从编写累积和函数开始:
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
[...]
2条答案
按热度按时间gcuhipw91#
你可以用
cumsum
来计算累积和,然后计算低于某个阈值n
的值的数量:1bqhqjot2#
可以在函数中放置一个
while
循环。如果达到限制,则停止进一步计算cumsum
。特别适用于较长的载体,例如