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
#  NA  2  3  3  4  4  2``` May 28, 2018 55 views

## 1 answer to this question.

You can use the sapply function, to loop over each element in vTR and take the first x values, then reverse them and take the cumulative sum over them and finally find the index when the value crosses the vTR[x] value.

Refer to the code below:

```sapply(seq_along(vTR),function(x) which.max(cumsum(rev(head(element, x)))>=vTR[x]))

# 1 2 3 3 4 4 2```

To get the exact expected output we can modify it by

```sapply(seq_along(vTR), function(x) {
if (sum(val)  >= vTR[x])
which.max(val >= vTR[x])
else
NA
})

# NA  2  3  3  4  4  2``` answered May 28, 2018 by
• 6,190 points

## How can I find number of rows in a dataframe, and how to find the number of rows that dont have null values

Use nrow() to find number of rows ...READ MORE

## With the help of tidyverse: how to rename a column to a variable name

With the help of Dplyr: rename function ...READ MORE

## What is the difference between [] and [[]] notations to access the elements of a list or dataframe in R?

R provides 3 basic indexing operators. Refer ...READ MORE

## How to limit output of a dataframe in R?

For randomly sampling a row/cell where a ...READ MORE

## Big Data transformations with R

Dear Koushik, Hope you are doing great. You can ...READ MORE

## Finding frequency of observations in R

You can use the "dplyr" package to ...READ MORE

The below is the code to perform ...READ MORE