获取相似对的总和并将结果相乘以获得同一数据框中的新列

Getting sum of similar pair and multiplying results to get a new column in same data frame

df1 <- data.frame(first_pair1_1=c(1,2,3,1,2,3,4),second_pair1_1=c(1,3,3,1,4,3,4),third_pair1_1=c(1,3,3,1,4,3,4),first_pair1_2=c(7,4,3,1,4,3,4),second_pair1_2=c(7,4,3,1,4,3,4),third_pair1_2=c(1,3,3,1,4,3,4),first_pair2_1=c(1,2,3,1,2,3,4),second_pair2_1=c(1,3,3,1,4,3,4),third_pair2_1=c(1,3,3,1,4,3,4),first_pair2_2=c(7,4,3,1,4,3,4),second_pair2_2=c(7,4,3,1,4,3,4),third_pair2_2=c(1,3,3,1,4,3,4))

我有上面的数据框,我正在尝试进行以下计算:

(first_pair1_1 * second_pair1_1 * third_pair1_1) + 
(first_pair1_2 * second_pair1_2 * third_pair1_2) + 
(first_pair2_1 * second_pair2_1 * third_pair2_1) + 
(first_pair2_2 * second_pair2_2 * third_pair2_2)

我想在同一数据框中的新列中获取结果。可能有更多对,但模式将相同。

这是一个基于 base R 的想法。我们遍历 1_1、1_2、... 的唯一后缀,并将包含每个后缀的所有列相乘(即 1_1*1_1*1_1 等等)。然后我们使用 rowSums 添加它们,即

ind <- unique(sub('.*pair', '', names(df1)))
rowSums(sapply(ind, function(i) Reduce(`*`, df1[grepl(i, names(df1))])))
#[1] 100 132 108   4 192 108 256
Reduce("+", lapply(split.default(df1, sub(pattern = "^[^_]*_", "", names(df1))),
                   function(a) Reduce("*", a)))
#[1] 100 132 108   4 192 108 256