首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何计算百分比并将其追加为新列?(示例中的最后两列)

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

Stack Overflow用户
提问于 2016-04-04 04:20:51
回答 1查看 59关注 0票数 1

我有一个巨大的数据集,我必须计算“每月儿童成本%和每月家长成本%”。我是新来的,并尽了最大努力。但没有多少幸运。请帮帮忙。

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

月子成本%=100/(该子月的总项目成本)*项目成本

第1行的示例: 100/100 * 70 = 70)

每月父级成本% =100/该父方在该月份的总项目成本)

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

请注意:在Monthly_Parent_Cost%中复制是可以的。我只能通过父和项获得不同的值。

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-04 06:40:14

您可以使用aggregate函数通过Child + Month + ItemParent + Month + Item聚合成本值。在此之后,您可以加入合并结果,并添加结果向量作为一个新的。

代码语言:javascript
复制
# 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)

我的公式可能不正确,因为我不清楚你想为这两栏加些什么。相应地调整代码。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36394524

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档