通过减少数据表来

时间:2019-07-11 18:23:09

标签: r data.table posix igraph

library(data.table)    
set.seed(333)
t <- data.table(old=seq(from=as.POSIXct("2013-01-01"), 
                          to=as.POSIXct("2013-01-02"), by="15 mins"), 
                dif=as.difftime(sample(seq(15,120,15),97,replace=TRUE),units="mins"))
t$new <- t$old + t$dif; t$foo <- rnorm(97); t$dif <- NULL
i <- data.table(id=1:3, start=sample(seq(from=as.POSIXct("2013-01-01"), 
                                           to=as.POSIXct("2013-01-01 22:00:00"), by="15 mins"),3))

> head(t)
                   old                 new        foo
1: 2013-01-01 00:00:00 2013-01-01 01:00:00 -1.5434407
2: 2013-01-01 00:15:00 2013-01-01 00:30:00 -0.2753971
3: 2013-01-01 00:30:00 2013-01-01 02:30:00 -1.5986916
4: 2013-01-01 00:45:00 2013-01-01 02:00:00 -0.6288528
5: 2013-01-01 01:00:00 2013-01-01 01:15:00 -0.8967041
6: 2013-01-01 01:15:00 2013-01-01 02:45:00 -1.2145590

> i
   id               start
1:  1 2013-01-01 22:00:00
2:  2 2013-01-01 21:00:00
3:  3 2013-01-01 13:30:00

这些数据显示了一个数据表,每个季度有一个时间间隔,以及其他变量,用foo表示。另一个数据表为每个id显示了时间窗口内的起点。 As in my previous question,我想从t删除行,以便仅将那些行保留在new[i] = old[i-1]的位置,从而为每个ID提供n个时间点的连续序列。结果应如下所示:

n=2
> ans
    id                 old                 new         foo
1:   1 2013-01-01 22:00:00 2013-01-01 23:00:00 -0.36643134  
2:   1 2013-01-01 23:00:00 2013-01-02 00:15:00  0.75903779
3:   2 2013-01-01 21:00:00 2013-01-01 22:15:00  0.98787668
4:   2 2013-01-01 22:15:00 2013-01-02 00:00:00  1.51498914
5:   3 2013-01-01 13:30:00 2013-01-01 15:30:00  1.95255430
5:   3 2013-01-01 15:30:00 2013-01-01 16:45:00  0.03339041

有人向我指出了以下解决方案,该解决方案适用于时间点为数字的示例数据:

set.seed(333)
t <- data.table(old=1002:2001, dif=sample(1:10,1000, replace=TRUE))
t$new <- t$old + t$dif; t$foo <- rnorm(1000); t$dif <- NULL
i <- data.table(id=1:3, start=sample(1000:1990,3))

library(igraph)
g <- graph_from_edgelist(as.matrix(t[,1:2]))
i[, t[old %in% subcomponent(g, start, "out")[1:n]], by=.(id)]

相反,实际问题具有POSIXct时间点,这会导致subcomponent(.)函数出现问题。有谁知道针对这些情况的解决方案?

PS。抱歉发布类似问题。我以为原来的帖子足够笼统,可以和其他人相关。但这对我来说太笼统了。

0 个答案:

没有答案