R:使用两个 ID 变量折叠行(一个 ID 嵌套在另一个中)

R: collapse rows using two ID variables (one ID nested in the other)

我有这样一个数据框:

user_id    year   
A          2011
A          2012
A          2012
A          2012
A          2013
A          2013
B          2011
B          2012
B          2012
B          2013
B          2013
B          2013
.
.
.

我想通过使用 user_idyear 折叠此数据框,以创建一个新列 count 来指示当年出现的次数。例如,对于 user A,有 one row of 2011three rows of 2012two rows of 2013。因此,这三年的 count 的值将分别为 1, 3, 2。数据框将折叠成如下所示:

user_id    year   count
A          2011     1
A          2012     3
A          2013     2
B          2011     1
B          2012     2
B          2013     3
.
.
.

我不知道如何利用 R 来完成此...任何帮助将不胜感激。

非常感谢!

-伊恩

我们可以使用 count 来自 dplyr

library(dplyr)
count(df1, user_id, year)