[R] Adding minutes to 24 hour time

Gustaf Rydevik gustaf.rydevik at gmail.com
Wed Mar 17 15:29:52 CET 2010


On Wed, Mar 17, 2010 at 2:57 PM, Hosack, Michael <mhosack at state.pa.us> wrote:
> Hi,
>
> Does anyone know how to add minutes (up to 100 min) to a 24 hour time, to create a new 24 hour time? I can't seem to find any documentation or examples explaining how to do this. The variables of interest are 'ARRIVE','WAIT', and 'DEPART' in the attached partial dataframe. I want 'DEPART' to be the "sum" of 'ARRIVE' and 'WAIT' in 24 hour format. Also, can anyone direct me to some relevant documentation?
>
> Thank you,
>
> Mike
>

If you convert all data to a date-and-time ?POSIXlt object, you can
just convert the minutes to seconds and add together with "+".
Another way would be the something like this:

addTime<-function(timeTxt,mins){
      start.time<-strsplit(timeTxt,":")
      start.time<-do.call("rbind",start.time)
      storage.mode(start.time)<-"numeric"
      hours<-mins%/%60
      mins.left<-mins%%60
      end.mins<-(start.time[,2]+mins.left)%%60
      end.hours<-(start.time[,1]+hours+(start.time[,2]+mins.left)%/%60)%%24
      end.time<-paste(end.hours,end.mins,sep=":")
     return(end.time)
}
addTime(c("15:23","7:00"),c(70,100))

or this:

addTime2<-function(timeTxt,mins){
orig.date<-as.POSIXct(paste("2001-01-01",timeTxt))
new.Date<-orig.date+mins*60
new.Date<-strsplit(as.character(new.Date)," ")
new.Time<-(sapply(new.Date,"[",2))
return(new.Time)
}
addTime2(c("15:23","7:00"),c(70,100))


Regards,
Gustaf
-- 
Gustaf Rydevik, M.Sci.
tel: +46(0)703 051 451
address:Essingetorget 40,112 66 Stockholm, SE
skype:gustaf_rydevik



More information about the R-help mailing list