Search code examples
rsumcycle

Finding of amount of elements by using special cycle with condition


I have simple dataset with digital values. For example, x<-c(3,4,6,7,8,4,5,3,4,3,5,6). I need to count number of elements by this way: i need to find minimal amount of elements which please condition: first element/sum of all elements should be greater than 0,95 or first element plus second element/sum of all elements should be greater than 0,95 and so on. For example, 3/58<0,95; 3+4/58<0,95; 3+4+6/58<0,95 and so on. I should stop when it will be greater than 0,95 and count number of elements that i used frm dataset. How can i do this?


Solution

  • min(which(cumsum(x)/sum(x) > 0.95))
    #[1] 12
    

    This gives which element in x first has a cumulative sum up to that point that exceeds 95% of the total of x.

    In this case, the total of x is 58, and 95% of that is 55.1. At the 11th element of x, the cumulative total is only 58-6 = 52, so you need all 12 elements to total more than 55.1.