Search code examples
rloopswhile-loopcumsum

R loop until condition matched, then go on


I have a dataframe with numerical values in one row. Now I want to calculate the cumsum of those rows, until >= 1. If this point is reached -> print for all those rows a counter, write in every row the cumsum for its counter, then look for the cumsum of the next rows.

Should look somewhow like this:

value    counter   cumsum
0.3      1         0.9
0.3      1         0.9
0.3      1         0.9
0.3      2         0.4
0.1      2         0.4
2        3         2

My problem is how to tell R to stop the cumsum, if >= than 1. Any ideas? Thank you in advance.


Solution

  • I don't know if I understood your problem correctly, but maybe this one here helps:

    value = round(runif(20, min = 0.1, max = 0.5), 1)
    
    csumVec = numeric(length(value))
    counterVec = numeric(length(value))
    startIndex = 1
    csum = 0
    counter = 1
    
    for(i in 1:length(value)) {
      csum = csum + value[i]
      if(csum > 1) {
        counterVec[startIndex:i] = counter
        csumVec[startIndex:i] = csum-value[i]
        startIndex = i
        counter = counter+1
        csum = value[i]
      }
      if(i == length(value)) {
        counterVec[startIndex:i] = counter
        csumVec[startIndex:i] = csum
      }
    }
    
    cbind(value, counterVec, csumVec)