【问题标题】:Getting sum of similar pair and multiplying results to get a new column in same data frame获取相似对的总和并将结果相乘以在同一数据框中获得新列
【发布时间】:2017-08-23 14:46:49
【问题描述】:
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)

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

【问题讨论】:

    标签: r dplyr tidyr


    【解决方案1】:

    这是一个基于 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
    

    【讨论】:

      【解决方案2】:
      Reduce("+", lapply(split.default(df1, sub(pattern = "^[^_]*_", "", names(df1))),
                         function(a) Reduce("*", a)))
      #[1] 100 132 108   4 192 108 256
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-04-12
        • 1970-01-01
        • 2019-10-06
        • 1970-01-01
        • 2014-04-21
        • 2020-01-08
        相关资源
        最近更新 更多