Loop to check if date contains some time interval in R -


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,] 

i need check if dates data frame c contains interval data frame c1 , create new data frame data dates contains 1 of time intervals.

i tried code simple numbers , worked when matrix n*n, need work on different c , c1 lenghts.

so maybe need library time , change loop lenght?

thanks in advance!

here's 1 approach:

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                   b # 1: 2016-01-04 07:59:59 2016-01-04 10:00:00 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 

data

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) 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -