每天按小组计数事件,包括r中的0
我想要每天计算事件的列,包括没有事件的日期。这是我数据的一个示例,尽管我的真实数据集具有超过100 id
的
dt <- structure(list(id = c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), date = c("1/01/2000", "2/01/2000", "2/01/2000",
"5/01/2000", "5/01/2000", "5/01/2000", "6/01/2000", "2/01/2000", "3/01/2000",
"3/01/2000", "4/01/2000", "4/01/2000", "4/01/2000", "4/01/2000",
"5/01/2000", "9/01/2000")), .Names = c("id", "date"),
row.names = c(NA, -16L), class = "data.frame")
我想要的内容:
date count 1 count 2
1/01/2000 0 0
2/01/2000 2 1
3/01/2000 0 2
4/01/2000 0 4
5/01/2000 3 1
6/01/2000 1 0
7/01/2000 0 0
8/01/2000 0 0
9/01/2000 0 1
我的真实数据将是1/01/2000
到31/12/2000
。我希望所有id
's拥有所有这些日期,即使某些日子内事件为零。
I want columns counting for events per day including dates without events. This is an example of my data although my real dataset has more than 100 ID
's
dt <- structure(list(id = c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), date = c("1/01/2000", "2/01/2000", "2/01/2000",
"5/01/2000", "5/01/2000", "5/01/2000", "6/01/2000", "2/01/2000", "3/01/2000",
"3/01/2000", "4/01/2000", "4/01/2000", "4/01/2000", "4/01/2000",
"5/01/2000", "9/01/2000")), .Names = c("id", "date"),
row.names = c(NA, -16L), class = "data.frame")
What I want is:
date count 1 count 2
1/01/2000 0 0
2/01/2000 2 1
3/01/2000 0 2
4/01/2000 0 4
5/01/2000 3 1
6/01/2000 1 0
7/01/2000 0 0
8/01/2000 0 0
9/01/2000 0 1
My real data will be dates from 1/01/2000
to 31/12/2000
. I want all ID
's to have all these dates, even if there were zero events during certain days.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
的方法
输出
是使用
data.table
这
Here is an approach using
data.table
Output:
If you know your dates, as you indicate in the post, you can use those directly:
Output:
Input:
我们可以使用
完成
,然后使用pivot_wider
重新设计为“ wide”。 OP以“日期”为月/天/年以“日期”格式显示了示例数据。如果原始数据以格式
YAURTAN-MANTAGE
,则将mdy(date)
更改为ymd(date)
output
We may use
complete
and then reshape to 'wide' withpivot_wider
. The OP showed the example data with format for 'date' asmonth/day/year
. If the original data is in formatyear-month-day
then change themdy(date)
toymd(date)
-output
的基本R选项
这是使用
表
+seq
+factor
,或者我们可以使用
reshape
更进一步+as.data.frame
如果我们想要data.frame输出
Here is a base R option using
table
+seq
+factor
which gives
Or, we can step further with
reshape
+as.data.frame
if we want data.frame outputwhich gives