4

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.

zx8754
  • 52,746
  • 12
  • 114
  • 209
Ben Irving
  • 461
  • 1
  • 6
  • 21

1 Answers1

8

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
zx8754
  • 52,746
  • 12
  • 114
  • 209