[R] function for handling time

Jim Lemon jim at bitwrit.com.au
Sun Oct 16 08:10:42 CEST 2011


On 10/16/2011 04:13 AM, Alaios wrote:
> Dear all
> I have the following time stamps (in the following format)
>
> MeasurementSet$TimeStamps
>         [,1] [,2] [,3] [,4] [,5]   [,6]
>    [1,] 2011    7    2   13   43 48.718
>    [2,] 2011    7    2   13   43 54.281
>    [3,] 2011    7    2   13   43 59.843
>    [4,] 2011    7    2   13   44  5.390
>    [5,] 2011    7    2   13   44 10.859
>    [6,] 2011    7    2   13   44 16.375
>    [7,] 2011    7    2   13   44 21.890
>    [8,] 2011    7    2   13   44 27.390
>    [9,] 2011    7    2   13   44 33.015
>   [10,] 2011    7    2   13   44 38.531
>   [11,] 2011    7    2   13   44 44.078
>   [12,] 2011    7    2   13   44 49.546
>   [13,] 2011    7    2   13   44 55.078
>   [14,] 2011    7    2   13   45  0.718
>   [15,] 2011    7    2   13   45  6.281
>   [16,] 2011    7    2   13   45 11.953
>   [17,] 2011    7    2   13   45 17.453
>   [18,] 2011    7    2   13   45 22.984
>
>
> I would like to write a function that will have inputs like that:
>          function(data, TimeStamps, timeBegin, timeEnd) {(not fixed though)
>
>
> and will return the index of start and the end.
>
> I need your help specify how the input arguments should look like  (something simple and compatible with the format I have already should be good).
> Then based on that two arguments, how I can search for start and end of timestamps inside the MeasurementSet$Timestamps and return the indexes of start and end of the time block?
>
Hi Alex,
I think what you are trying to do is this:

TimeStamps<-matrix(
  c(2011,7,2,13,43,48.718,
   2011,7,2,13,43,54.281,
   2011,7,2,13,43,59.843,
   2011,7,2,13,44,5.390,
   2011,7,2,13,44,10.859,
   2011,7,2,13,44,16.375,
   2011,7,2,13,44,21.890,
   2011,7,2,13,44,27.390,
   2011,7,2,13,44,33.015,
   2011,7,2,13,44,38.531,
   2011,7,2,13,44,44.078,
   2011,7,2,13,44,49.546,
   2011,7,2,13,44,55.078,
   2011,7,2,13,45,0.718,
   2011,7,2,13,45,6.281,
   2011,7,2,13,45,11.953,
   2011,7,2,13,45,17.453,
   2011,7,2,13,45,22.984),
  ncol=6,byrow=TRUE)

findBeginEnd<-function(x,timeBegin,timeEnd) {
  bits2date<-function(x) {
   the_date<-strptime(paste(x,c("-","-"," ",":",":",""),
    sep="",collapse=""),format="%Y-%m-%d %H:%M:%S")
   return(the_date)
  }
  dimx<-dim(x)
  timeBegin<-strptime(timeBegin,format="%Y-%m-%d %H:%M:%S")
  timeEnd<-strptime(timeEnd,format="%Y-%m-%d %H:%M:%S")
  start_index<-1
  nextdate<-bits2date(x[1,])
  while(nextdate < timeBegin && start_index < dimx[1]) {
   start_index<-start_index + 1
   nextdate<-bits2date(x[start_index,])
  }
  end_index<-start_index
  while(timeEnd > nextdate && end_index < dimx[1]) {
   end_index<-end_index + 1
   nextdate<-bits2date(x[end_index,])
  }
  return(list(start=start_index,end=end_index))
}

findBeginEnd(TimeStamps,"2011-7-2 13:44:20.0","2011-7-2 13:45:12.0")

Jim



More information about the R-help mailing list