Search code examples
rloopsvectordifference

Sum up the differences between every element of a vector and a given threshold


I have the following vector:

my_vec <- c(2,3,5,3,5,2,6,7,2,4,6,8)

threshold <- 4

Is there a way to sum up the differences of all smaller elements of my_vec compared to the threshold value?

So the expected result on this example should be 8 (2+1+0+1+0+2+0+0+2+0+0+0) For my purpose, the sum (8) is all I need (I don't need the difference between every element). I tried this by using a loop but unfortunately, there are several vectors of different length so I can't loop from 1:12 (as on the above vector) on a vector which has only 10 elements.


Solution

  • First subset elements below threshold and then sum difference to threshold:

    threshold <- 4
    sum((threshold - my_vec[my_vec < threshold]))
    
    # [1] 8