计算每组中的行数 [英] Count number of rows within each group

查看:101
本文介绍了计算每组中的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,我想计算每个组中的行数。我非常地使用聚合函数来计算数据如下:

  df2 <  -  aggregate(x〜Year + Month,data = df1,sum)

喜欢计算观察值,但似乎找不到 FUN 的正确参数。直觉上,我以为会如下:

  df2<  -  aggregate(x〜Year + Month,data = df1,计数)

但是,没有这样的运气。



任何想法?






一些玩具数据:

  set.seed(2)
df1 < - data.frame(x = 1:20,
Year = sample(2012:2014,20)replace = TRUE )
Month = sample(month.abb [1:3],20,replace = TRUE))


解决方案

还有 df2< - count(x,c('Year','Month')) (plyr包)


I have a dataframe and I would like to count the number of rows within each group. I reguarly use the aggregate function to sum data as follows:

df2 <- aggregate(x ~ Year + Month, data = df1, sum)

Now, I would like to count observations but can't seem to find the proper argument for FUN. Intuitively, I thought it would be as follows:

df2 <- aggregate(x ~ Year + Month, data = df1, count)

But, no such luck.

Any ideas?


Some toy data:

set.seed(2)
df1 <- data.frame(x = 1:20,
                  Year = sample(2012:2014, 20, replace = TRUE),
                  Month = sample(month.abb[1:3], 20, replace = TRUE))

解决方案

There is also df2 <- count(x, c('Year','Month')) (plyr package)

这篇关于计算每组中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆