Problem
我想找到一个优雅的tidyverse解决方案来创建每个n列的m乘积之和.我不想使用位置匹配,它应该是可推广的.
我摆弄了purrr::pmap_dbl(select(., ends_with(i)), prod)
个,但没走多远.
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
第一排:5*3+9*3+2*2 = 46
;第二排: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