Outsourcing this to a function creates duplicate work (even the way you did it's just a sum)
I think you can put the next part just in the else

or, maybe it's not so bad the way it is, it will reduce the calculations if there are no nans