Move sum over r outside of loop