Problem
I want to find an elegant tidyverse solution to create a sum of m products of each n colums. I don't want to use positional matching and it should be generalizable.
I fiddled around with purrr::pmap_dbl(select(., ends_with(i)), prod) but did not get very far.
Example for m = 3 and n = 2
library(tidyverse)
df <- tibble(
x_0 = c(5,6),
x_1 = c(9,1),
x_2 = c(2,1),
y_0 = c(3,2),
y_1 = c(3,2),
y_2 = c(1,3)
)
df
> df
# A tibble: 2 × 6
# x_0 x_1 x_2 y_0 y_1 y_2
#<dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 5 9 2 3 3 1
# 6 1 1 2 2 3
I want to calculate the sum of the products rowise:
sum_of_products = x_0 * y_0 + x_1 * y_1 + x_2 + y_2
First row: 5*3+9*3+2*2 = 46; Second row: 6*2+1*2+1*3 = 17
Desired output
df_with_sum_of_products
# x_0 x_1 x_2 y_0 y_1 y_2 sum_of_products
#<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
# 5 9 2 3 3 1 46
# 6 1 1 2 2 3 17