A=c("a","b","c","d","e","f","g","h","h","j")
B=c(2016-01-04 08:00:00, 2016-01-04 08:02:26, 2016-01-04 09:15:15,
2016-01-04 15:16:03, 2016-01-05 12:35:12, 2016-01-05 16:35:05,
2016-01-06 08:20:35, 2016-01-06 08:20:36, 2016-01-07 03:09:00,
2016-01-07 07:16:00)
a=as.data.frame(A)
b=as.data.frame(B)
c=cbind(a,b)
A1=c(2016-01-04 07:59:59, 2016-01-05 12:35:12, 2016-01-06 16:36:00,
2016-01-07 03:08:00, 2016-01-08 09:00:00, 2016-01-09 09:00:00)
B1=c(2016-01-04 10:00:00, 2016-01-05 12:40:00, 2016-01-06 16:38:53,
2016-01-07 07:10:00, 2016-01 08 23:50:42, 2016-01-09 17:45:32)
a1=as.data.frame(A1)
b1=as.data.frame(B1)
c1=cbind(a1,b1)
z=0
E=matrix(NA,nrow=length(c[,1]),ncol=length(c1[,1]))
E
for(i in 1:length(c[,1]))
{
N<-c[i,2]
for(j in 1:length(c1[,1]))
{
z[j]=(N <= c1[j,2] & N >= c1[j,1])
}
E[,i]=z
}
E
g=which(E == 1,arr.ind=T)
n=g[,2]
s<-c[n,]
我需要检查数据帧c中的日期是否包含数据帧c1的某个间隔,然后创建新的数据框,其中日期包含一个时间间隔的数据。
我用简单的数字尝试了这个代码并且它工作但是当矩阵是n * n时,我需要它可以在不同的c和c1长度上工作。
所以也许我需要一些时间库来改变lenght的循环?
提前致谢!
答案 0 :(得分:1)
这是一种方法:
library(data.table)
setDT(c1, key = c("A1", "B1"))
setDT(c)[, C:=B]
foverlaps(c, c1, by.x=c("C", "B"))[!is.na(A1) & !is.na(B1)][, C:=NULL][]
# A1 B1 A B
# 1: 2016-01-04 07:59:59 2016-01-04 10:00:00 a 2016-01-04 08:00:00
# 2: 2016-01-04 07:59:59 2016-01-04 10:00:00 b 2016-01-04 08:02:26
# 3: 2016-01-04 07:59:59 2016-01-04 10:00:00 c 2016-01-04 09:15:15
# 4: 2016-01-05 12:35:12 2016-01-05 12:40:00 e 2016-01-05 12:35:12
# 5: 2016-01-07 03:08:00 2016-01-07 07:10:00 h 2016-01-07 03:09:00
数据强>
A=c("a","b","c","d","e","f","g","h","h","j")
B=c("2016-01-04 08:00:00", "2016-01-04 08:02:26", "2016-01-04 09:15:15",
"2016-01-04 15:16:03", "2016-01-05 12:35:12", "2016-01-05 16:35:05",
"2016-01-06 08:20:35", "2016-01-06 08:20:36", "2016-01-07 03:09:00",
"2016-01-07 07:16:00")
a=as.data.frame(A)
b=as.data.frame(B)
c=cbind(a,b)
A1=c("2016-01-04 07:59:59", "2016-01-05 12:35:12", "2016-01-06 16:36:00",
"2016-01-07 03:08:00", "2016-01-08 09:00:00", "2016-01-09 09:00:00")
B1=c("2016-01-04 10:00:00", "2016-01-05 12:40:00", "2016-01-06 16:38:53",
"2016-01-07 07:10:00", "2016-01-08 23:50:42", "2016-01-09 17:45:32")
a1=as.data.frame(A1)
b1=as.data.frame(B1)
c1=cbind(a1,b1)
c$B <- as.POSIXct(c$B)
c1$B1 <- as.POSIXct(c1$B1)
c1$A1 <- as.POSIXct(c1$A1)