如何根据时间和阈值对时间序列data.frame进行子集?
我有这样的数据:
year <- seq(2000, 2009, 1)
v1 <- sample(1:10, 10, replace=T)
df <- data.frame(year, v1)看起来是这样的:
> df
year v1
1 2000 9
2 2001 4
3 2002 5
4 2003 4
5 2004 5
6 2005 3
7 2006 3
8 2007 3
9 2008 9
10 2009 6我想按顺序年份的组对数据进行子集,在v1上的求和得分超过10。
在这个例子中,第一个子集应该保存2000年和2001年的观测结果。第二部分应包含2002年、2003年和2004年的观测结果。
真正的数据大约有800万次观测,覆盖了120年。
发布于 2016-10-05 19:59:50
您可以使用cumsum函数实现自定义的Reduce,在总数超过10时重置和,同时将计数增量为组变量:
library(data.table)
transpose(Reduce(function(x, y) if(x[1] > 10) c(y, x[2]+1) else c(x[1] + y, x[2]),
init = c(0, 1), df$v1, accumulate = T))[[2]][-1]
# here the init parameter will take two parameters, the first one keep track of the cumsum,
# and the second one serves as a group variable, when the sum exceeds 10, reset the sum to
# zero and increase the group variable by one
# [1] 1 1 2 2 2 3 3 3 3 4运行超过1,000万次观测向量需要大约20秒:
v = sample(1:10, 10000000, replace = T)
system.time(transpose(Reduce(function(x, y) if(x[1] > 10) c(y, x[2]+1) else c(x[1] + y, x[2]), init = c(0, 1), v, accumulate = T))[[2]])
# user system elapsed
# 19.509 0.552 20.081 https://stackoverflow.com/questions/39882212
复制相似问题