您可以使用plyr包和专门的count功能。使用您的数据,我们可以执行以下操作:
require(plyr)
toydat
Purchases WeeksSinceFirstPurcahse
1 1 10.1
2 1 4.2
3 1 4.2
4 2 2.4
5 3 1.0
6 2 2.4
str(toydat)
'data.frame': 6 obs. of 2 variables:
$ Purchases : int 1 1 1 2 3 2
$ WeeksSinceFirstPurcahse: num 10.1 4.2 4.2 2.4 1 2.4
ddply(toydat, .(Purchases), function(x) count(x, "WeeksSinceFirstPurcahse"))
Purchases WeeksSinceFirstPurcahse freq
1 1 4.2 2
2 1 10.1 1
3 2 2.4 2
4 3 1.0 1
编辑以添加计数函数示例:
count(toydat,.(Purchases,WeeksSinceFirstPurchase))
Purchases WeeksSinceFirstPurchase freq
1 1 4.2 2
2 1 10.1 1
3 2 2.4 2
4 3 1.0 1