[R] midpoint between two dates
Pete Brecknock
Peter.Brecknock at bp.com
Mon Nov 18 02:58:35 CET 2013
eric wrote
> Is there an easy way to get the midpoint between two dates in a data frame
> ? If I have a dataframe that looks like this :
>
> head(x)
> instDay remDay exp.time mpy
> 1 2006-02-02 2006-04-03 60 0.2
> 2 2006-04-17 2006-08-17 122 0.3
> 4 2006-08-17 2006-10-23 67 0.4
> 6 2006-10-23 2007-04-03 162 0.3
> 8 2007-04-03 2007-05-15 42 0.8
> 11 2007-05-15 2007-08-01 78 0.3
>
> I would like an additional column that represents the midpoint between
> instDay and newDay. For those days where the time difference is an odd
> number and the midpoint would not be a specific date, it would be OK to
> round up or round down.
>
> I thought about converting both columns to numeric values and taking the
> difference, dividing by two with modulus operator, then adding to the
> first column and finally converting back to a date. But I'm think there
> must be a more simple way.
How about ...
date1 = as.Date(c("2013-10-10","2013-11-15","2013-12-25"))
date2 = as.Date(c("2013-10-20","2013-11-20","2013-12-30"))
df <- data.frame(id=c(1,2,3),date1,date2)
df$mid <- df$date1 + floor((df$date2-df$date1)/2)
print(df)
id date1 date2 mid
1 1 2013-10-10 2013-10-20 2013-10-15
2 2 2013-11-15 2013-11-20 2013-11-17
3 3 2013-12-25 2013-12-30 2013-12-27
HTH
Pete
--
View this message in context: http://r.789695.n4.nabble.com/midpoint-between-two-dates-tp4680649p4680654.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list