Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sumproduct by condition in a data frame in R

Consider the following data frame:

df <- data.frame(row_id = c("r1","r2","r3","r4","r1","r2","r3","r4"),
                 v1 = c(3,2,5,2,5,2,6,4),
                 v2 = c(4,3,5,3,7,4,6,7))

I want take the sum-product by "row_id". That is, for the rows with the row_id: "r1" I want to do the following calculation: (3*4)+(5*7). And so on.

Thus, I will finally have the following matrix:

df1 <- data.frame(row_id = c("r1","r2","r3","r4"),
                 v1 = c(47,14,61,34))

Any help will be really appreciated.

Thanks.

like image 730
Michael Avatar asked Oct 15 '19 17:10

Michael


1 Answers

Similar but slightly shorter:

dplyr::count(df, row_id, wt = v1*v2)
like image 110
Jon Spring Avatar answered Nov 03 '22 01:11

Jon Spring