I am trying to get an output consisting of the number of elements needed to be added to sum a certain value.
Below is a sample code considered.
  # value to reach
  vTR = c(10,15,12,13,10,15,10)
  # element to sum
  element = c(9,6,5,2,1,9,1)
  magicFoo(vTR, element) 
  # should return c(NA, 2, 3, 3, 4, 4, 2) 
  # 10 ~ NA, 15 <= 9+6, 12 <= 5+6+9, 13 <= 2+5+6, 10 <= 1+2+5+6...
For example, if I am looking for some kind of average where k is calculated dynamically I can do it with a for loop but I am finding a more elegant way to do this.
vTR = c(10,15,12,13,10,15,10)
# element to sum
element = c(9,6,5,2,1,9,1)
res = c()
j = 1
k = 0
sumE = 0
for (i in 1:length(vTR)){
  k = k+1
  sumE = sum(element[j:k])
  if (sumE < vTR[i]) {
    res[length(res)+1] = NA
    next
  }
  repeat {
    j = j + 1
    sumE = sum(element[j:k])
    if (sumE < vTR[i]) {
      j = j-1
      res[length(res)+1] = k-j +1 
      break
    }
  }
}
# > res
# [1] NA  2  3  3  4  4  2