[Solved] Sum values in matrix with if statement


The second column is binary. So one way would be to change it to logical vector, subset the values that correspond to ‘ON’ and ‘OFF’ (i.e. 1 and 0), get the difference of the sum of both and multiply with 40.

 40*(sum(ccmix[,1][!!ccmix[,2]]) - sum(ccmix[,1][!ccmix[,2]]))

The negate function (!) converts 0 to TRUE and 1 to FALSE. If we do the double negate (!!), 1 becomes TRUE and 0 as FALSE. Instead of the negation, we can wrap with as.logical to get 1 converted to TRUE, 0 to FALSE.

solved Sum values in matrix with if statement