R 每两分钟将事件列表转换为一系列事件数
两个密切相关的员额是和。我还没能把这两个都翻译成我的真实情况 这是一个时间向量:R 每两分钟将事件列表转换为一系列事件数,r,time,bins,R,Time,Bins,两个密切相关的员额是和。我还没能把这两个都翻译成我的真实情况 这是一个时间向量: start.time = as.POSIXct("2013-06-20 01:00:00") x = start.time + runif(5, min = 0, max = 8*60) x = x[order(x)] x # [1] "2013-06-20 01:00:30 EDT" "2013-06-20 01:00:57 EDT" # [3] "2013-06-20 01:01:43 EDT" "2013-0
start.time = as.POSIXct("2013-06-20 01:00:00")
x = start.time + runif(5, min = 0, max = 8*60)
x = x[order(x)]
x
# [1] "2013-06-20 01:00:30 EDT" "2013-06-20 01:00:57 EDT"
# [3] "2013-06-20 01:01:43 EDT" "2013-06-20 01:04:01 EDT"
# [5] "2013-06-20 01:04:10 EDT"
接下来,这里是两个分钟标记的向量:
y = seq(as.POSIXct("2013-06-20 01:00:00"), as.POSIXct("2013-06-20 01:06:00"), 60*2)
y
# [1] "2013-06-20 01:00:00 EDT" "2013-06-20 01:02:00 EDT"
# [3] "2013-06-20 01:04:00 EDT" "2013-06-20 01:06:00 EDT"
我想要一种快速、灵活、可扩展的方法来生成x
元素的计数,这些计数落在y
每个元素右侧的两分钟箱子中,如下所示:
y count.x
1 2013-06-20 01:00:00 3
2 2013-06-20 01:02:00 0
3 2013-06-20 01:04:00 2
4 2013-06-20 01:06:00 0
怎么样
as.data.frame(table(cut(x, breaks=c(y, Inf))))
Var1 Freq
1 2013-06-20 01:00:00 3
2 2013-06-20 01:02:00 0
3 2013-06-20 01:04:00 2
4 2013-06-20 01:06:00 0
怎么样
as.data.frame(table(cut(x, breaks=c(y, Inf))))
Var1 Freq
1 2013-06-20 01:00:00 3
2 2013-06-20 01:02:00 0
3 2013-06-20 01:04:00 2
4 2013-06-20 01:06:00 0
这是一个解决问题的函数,的运行速度比
表(cut(…)
快得多:
get.bin.counts = function(x, name.x = "x", start.pt, end.pt, bin.width){
br.pts = seq(start.pt, end.pt, bin.width)
x = x[(x >= start.pt)&(x <= end.pt)]
counts = hist(x, breaks = br.pts, plot = FALSE)$counts
dfm = data.frame(br.pts[-length(br.pts)], counts)
names(dfm) = c(name.x, "freq")
return(dfm)
}
在这个例子中,我的函数比
table(cut(…)
的运行速度快了10倍多一点。这归功于cut
,它指出,“与table(cut(x,br))
相比,hist(x,br,plot=FALSE)
更高效,内存消耗更少。”下面是一个解决问题的函数,比table(cut(…)
运行得更快:
get.bin.counts = function(x, name.x = "x", start.pt, end.pt, bin.width){
br.pts = seq(start.pt, end.pt, bin.width)
x = x[(x >= start.pt)&(x <= end.pt)]
counts = hist(x, breaks = br.pts, plot = FALSE)$counts
dfm = data.frame(br.pts[-length(br.pts)], counts)
names(dfm) = c(name.x, "freq")
return(dfm)
}
在这个例子中,我的函数比table(cut(…)
的运行速度快了10倍多一点。归功于cut
,它指出,“与表(cut(x,br))
相比,hist(x,br,plot=FALSE)
更高效,占用内存更少。”