直到阈值的数字的和列表

时间:2021-02-03 21:27:43

I have a list of integers that I want to sum until a threshold value is met, and then be able to access the index at which the threshold is reached.

我有一个要求和的整数列表,直到满足阈值,然后才能访问达到阈值的索引。

Something like:

喜欢的东西:

summing <- function(i){
sum = sum + list[i]
index = i
while(sum < thresholdValue){
summing(i++)
}}

However, I'm not well versed on writing functions in R so not 100% sure on how this should be done.

但是,我不太擅长在R中编写函数,所以不能100%确定应该怎么做。

1 个解决方案

#1


4  

Try this example:

试试这个例子:

#data
x <- 1:10 

#set threshold
thresholdValue <- 13

#index
ix <- length(which(cumsum(x) <= thresholdValue))
# 4

#sum
sum(x[1:ix])
#[1] 10

#1


4  

Try this example:

试试这个例子:

#data
x <- 1:10 

#set threshold
thresholdValue <- 13

#index
ix <- length(which(cumsum(x) <= thresholdValue))
# 4

#sum
sum(x[1:ix])
#[1] 10