Sum product by row across two dataframes/matrix in r

runningbirds picture runningbirds · Apr 10, 2015 · Viewed 7.4k times · Source

I have two data frames, each with two columns. They could be matrices with same dimensions if that helps in the calculations.

What I want to do is the sum product of these data frames of the respective positions/rows.

For example the solution would be the following in one column.

 21 = 1*1+10*2
 42 = 2*1 +20*2
63 = 3*1 + 20*2

 a=data.frame(c_1=c(1,2,3),c_2=c(10,20,30))
  b=data.frame(c2_1=c(1,1,1),c2_2=c(2,2,2))

Answer

Mamoun Benghezal picture Mamoun Benghezal · Apr 10, 2015

you can try something like

rowSums(a*b)
[1] 21 42 63