我有一个巨大的数据集,我必须计算“每月儿童成本%和每月家长成本%”。我是新来的,并尽了最大努力。但没有多少幸运。请帮帮忙。
在我的原始数据集中,我有Prent/Child/Item/Month/Cost数据。我必须计算两个新列.
月子成本%=100/(该子月的总项目成本)*项目成本
第1行的示例: 100/100 * 70 = 70)
每月父级成本% =100/该父方在该月份的总项目成本)
第一行的例子: 100/345 * 215 (该母公司的牛奶总成本)= 62.3
请注意:在Monthly_Parent_Cost%中复制是可以的。我只能通过父和项获得不同的值。
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发布于 2016-04-04 06:40:14
您可以使用aggregate函数通过Child + Month + Item和Parent + 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)我的公式可能不正确,因为我不清楚你想为这两栏加些什么。相应地调整代码。
https://stackoverflow.com/questions/36394524
复制相似问题