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

时间:2016-04-04 04:20:51

标签: r

我有一个庞大的数据集,我必须计算"每月儿童费用%和每月父费用%"。我是R的新手并且尽我所能。但不是很多。请帮忙。

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

每月儿童费用% = 100 /(该孩子特定月份的项目总费用)*项目费用

第1行示例: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

1 个答案:

答案 0 :(得分:1)

您可以使用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)

P.S。我的公式可能不正确,因为我不清楚你想要对两列进行聚合。相应地调整您的代码。