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.
Similar but slightly shorter:
dplyr::count(df, row_id, wt = v1*v2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With