Rilcon42 Rilcon42 - 2 months ago 7
R Question

get sum of the product of two columns

Can someone explain how my order of operations for the R fuctions below is wrong? I expected to multiply across each row then sum the result, but the answer I got was very different.

qqq<-data.frame(c(1,2,3),c(4,5,6))
library(dplyr)
qqq%>%sum(.[,1]*.[,2]) #returns: 53

# answer I expected: 1*4+2*5+3*6 = 32

Answer

We can try

qqq %>%
     Reduce(`*`, .) %>%
     sum
#[1] 32