R如何计算百分比并作为新列追加?(示例中的最后两列)



我有一个巨大的数据集,我必须计算"每月子成本%和每月父成本%"。我是R的新手,已经尽力了。但运气并不好。请帮忙。

在我的原始数据集中,我有Prent/Child/Item/Month/Cost数据我必须计算2个新列

每月子项成本%=100/(该子项在特定月份的总项目成本)*项目成本

第一行示例:100/100*70=70)

每月上级成本%=100/该上级当月的项目总成本)*项目成本

第一行示例:100/345*215(该父母的牛奶总成本)=62.3

请注意:Monthly_Parent_Cost%中可以有重复项。我只能通过Parent和Item获得不同的值。

Parent  Child   Item    Month   Cost    Monthly_Child_Cost%     Monthly_Parent_Cost%
    1001    22  Milk    Jan     70      70      62.32
    1001    22  Bread   Jan     20      20      31.88
    1001    22  Eggs    Jan     10      10      5.8
    1001    22  Milk    Feb     60      60      62.32
    1001    22  Bread   Feb     40      40      31.88
    1001    11  Milk    Mar     40      40      62.32
    1001    11  Bread   Mar     50      50      31.88
    1001    11  Eggs    Mar     10      10      5.8
    1001    11  Milk    Apr     45      100     62.32
    1002    44  Milk    Jan     20      20      40.3
    1002    44  Bread   Jan     40      40      33.2
    1002    44  Eggs    Jan     40      40      26.3
    1002    44  Milk    Feb     34      34      40.3
    1002    44  Bread   Feb     66      66      33.2
    1002    55  Milk    Mar     20      20      40.3
    1002    55  Bread   Mar     20      20      33.2
    1002    55  Eggs    Mar     60      60      26.3
    1002    55  Milk    Apr     79      100     40.3

您可以使用aggregate函数按Child + Month + ItemParent + Month + Item聚合成本值。之后,您可以连接合并结果,并将结果向量添加为新向量。

# Aggregate
childCosts <- aggregate(x = ds$Cost, by=list(ds$Child, ds$Month, ds$Item), FUN=sum)
# modify column names for easy merge
colnames(childCosts) <- c("Child", "Month", "Item", "Monthly_child_total")
ds2 <- merge(ds, childCosts)
# Compute desired result
ds2$Monthly_Child_Cost_Pct <- ds2$Cost*100/(ds2$Monthly_child_total)

附言:我的公式可能不正确,因为我不清楚你想为这两列汇总什么。相应地调整您的代码。

最新更新