计算随机观察总和每周在R中的总和
我有一个随机的数据集,有时是不频繁的事件,我想将其视为每周的总和。由于它们的随机性不是线性的,因此到目前为止我尝试过的其他示例不适用。
数据与此相似:
df_date <- data.frame( Name = c("Jim","Jim","Jim","Jim","Jim","Jim","Jim","Jim","Jim","Jim",
"Sue","Sue","Sue","Sue","Sue","Sue","Sue","Sue","Sue","Sue"),
Dates = c("2010-1-1", "2010-1-2", "2010-01-5","2010-01-17","2010-01-20",
"2010-01-29","2010-02-6","2010-02-9","2010-02-16","2010-02-28",
"2010-1-1", "2010-1-2", "2010-01-5","2010-01-17","2010-01-20",
"2010-01-29","2010-02-6","2010-02-9","2010-02-16","2010-02-28"),
Event = c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1) )
我要做的是创建一个新表,其中包含日历年中每周的事件之和。
在这种情况下,产生这样的东西:
Name Week Events
Jim 1 3
Sue 1 3
Jim 2 0
Sue x ... x
and so on...
I have a dataset of random, sometimes infrequent, events that I want to count as a sum per week. Due to the randomness they are not linear so other examples I have tried so far are not applicable.
The data is similar to this:
df_date <- data.frame( Name = c("Jim","Jim","Jim","Jim","Jim","Jim","Jim","Jim","Jim","Jim",
"Sue","Sue","Sue","Sue","Sue","Sue","Sue","Sue","Sue","Sue"),
Dates = c("2010-1-1", "2010-1-2", "2010-01-5","2010-01-17","2010-01-20",
"2010-01-29","2010-02-6","2010-02-9","2010-02-16","2010-02-28",
"2010-1-1", "2010-1-2", "2010-01-5","2010-01-17","2010-01-20",
"2010-01-29","2010-02-6","2010-02-9","2010-02-16","2010-02-28"),
Event = c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1) )
What I'm trying to do is create a new table that contains the sum of events per week in the calendar year.
In this case producing something like this:
Name Week Events
Jim 1 3
Sue 1 3
Jim 2 0
Sue x ... x
and so on...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更新多年来的OP请求:
我们可以使用
ISOWEEK
也可以从lubridate
而不是Week
或:
我们可以按以下方式添加年度:
我们可以使用
lubridate
s周
week 转换字符date
dates 使用lubridate s
ymd
函数。然后,我们可以使用
count
,这是group_by(name,Week)%&gt;%总结的简称(count = n())
:
Update OP request for multiple years:
We could use
isoweek
also fromlubridate
instead ofweek
OR:
We could add the year as follows:
We could use
lubridate
sWeek
function after transforming characterDates
to date format withlubridate
symd
function.Then we can use
count
which is the short forgroup_by(Name, Week) %>% summarise(Count = n())
:
这是一种为每个人带来每个ISO周的方法,当该周没有事件的事件时,零是:输出:
输出:
Here is an approach that gets you each ISO week for each individual, with zeros when there are no events for that week for that individual:
Output: