我需要在ddply或者聚合中使用group by,如果这更容易的话.我不确定如何做到这一点,因为我需要使用cumsum作为我的聚合函数.这就是我的数据:
level1 level2 hour product
A tea 0 7
A tea 1 2
A tea 2 9
A coffee 17 7
A coffee 18 2
A coffee 20 4
B coffee 0 2
B coffee 1 3
B coffee 2 4
B tea 21 3
B tea 22 1
Run Code Online (Sandbox Code Playgroud)
预期产量:
A tea 0 7
A tea 1 9
A tea 2 18
A coffee 17 7
A coffee 18 9
A coffee 20 13
B coffee 0 2
B coffee 1 5
B coffee 2 9
B tea 21 3
B tea 22 4
Run Code Online (Sandbox Code Playgroud)
我试过用
ddply(dd,c("level1","level2","hour"),summarise,cumsum(product))
Run Code Online (Sandbox Code Playgroud)
但这并不总结我认为是因为小时栏被用于分组而被它拆分......我想......我不确定我是否完全理解聚合在这里如何运作.有什么办法可以使用aggregate或ddply获得所需的输出吗?
A5C*_*2T1 16
这是基本R使用ave和的解决方案within:
within(mydf, {
cumsumProduct <- ave(product, level1, level2, FUN = cumsum)
})
# level1 level2 hour product cumsumProduct
# 1 A tea 0 7 7
# 2 A tea 1 2 9
# 3 A tea 2 9 18
# 4 A coffee 17 7 7
# 5 A coffee 18 2 9
# 6 A coffee 20 4 13
# 7 B coffee 0 2 2
# 8 B coffee 1 3 5
# 9 B coffee 2 4 9
# 10 B tea 21 3 3
# 11 B tea 22 1 4
Run Code Online (Sandbox Code Playgroud)
当然,如果要删除现有产品列,可以将命令更改为以下内容以覆盖当前"产品"列:
within(mydf, {
product <- ave(product, level1, level2, FUN = cumsum)
})
Run Code Online (Sandbox Code Playgroud)
您当前的方法无法正常工作,因为您已将"小时"作为您的分组变量之一.换句话说,它看到"A +茶+ 0"的组合与"A +茶+ 1"不同,但是根据您想要的输出,您似乎只想要"A +茶"的组合是组.
aggregate将无法按预期工作,因为它会将所有内容压缩为data.frame与"level1"和"level2"的唯一组合数相同的行数,在本例中为4行.聚合列将是list.这些值是正确的,但它没那么有用.
这是aggregate和它的输出:
> aggregate(product ~ level1 + level2, mydf, cumsum)
level1 level2 product
1 A coffee 7, 9, 13
2 B coffee 2, 5, 9
3 A tea 7, 9, 18
4 B tea 3, 4
Run Code Online (Sandbox Code Playgroud)
你应该使用transform而不是summarise:
# you should probably order your `level2` first
dd$level2 <- factor(dd$level2, levels=c("tea", "coffee"))
# and transform using level1 and level2 alone, not hour
# if you use hour, the groups will be for each row
ddply(dd, .(level1, level2), transform, product=cumsum(product))
# level1 level2 hour product
# 1 A tea 0 7
# 2 A tea 1 9
# 3 A tea 2 18
# 4 A coffee 17 7
# 5 A coffee 18 9
# 6 A coffee 20 13
# 7 B tea 21 3
# 8 B tea 22 4
# 9 B coffee 0 2
# 10 B coffee 1 5
# 11 B coffee 2 9
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4848 次 |
| 最近记录: |