[R] rollapply and difftime

MacQueen, Don macqueen1 at llnl.gov
Fri May 27 02:09:20 CEST 2016


You want the number of days between dates?
Does this do the trick?

dts <- Sys.Date()+ c(1,2,3,5,6,9)
dts[-1] - dts[-length(dts)]

Time differences in days
[1] 1 1 2 1 3



-- 
Don MacQueen

Lawrence Livermore National Laboratory
7000 East Ave., L-627
Livermore, CA 94550
925-423-1062





On 5/26/16, 4:59 PM, "R-help on behalf of Morway, Eric"
<r-help-bounces at r-project.org on behalf of emorway at usgs.gov> wrote:

>Technically, the code below works and results in a column that I'm
>interested in working with for further processing.  However, it is both
>inefficient on lengthy (>100 yr) daily time series and is, frankly, not
>the
>R way of doing things.  Using the 'Daily' data.frame provided below, I'm
>interested to know the propeR way of accomplishing this same task in an
>efficient manner.  I tried combinations of rollapply and difftime, but was
>unsuccessful.  Eric
>
>Daily <- read.table(textConnection("     Date        Q
>1911-04-01 4.530695
>1911-04-02 4.700596
>1911-04-03 4.898814
>1911-04-04 5.097032
>1911-04-05 5.295250
>1911-04-06 6.569508
>1911-04-07 5.861587
>1911-04-08 5.153666
>1911-04-09 4.445745
>1911-04-10 3.737824
>1911-04-11 3.001586
>1911-04-12 3.001586
>1911-04-13 2.350298
>1911-04-14 2.661784
>1911-04-16 3.001586
>1911-04-17 2.661784
>1911-04-19 2.661784
>1911-04-28 3.369705
>1911-04-29 3.001586
>1911-05-20 2.661784"),header=TRUE)
>
>Daily$Date <- as.Date(Daily$Date)
>Daily$tmdiff <- NA
>for(i in seq(2,length(Daily$Date),by=1)){
>  Daily$tmdiff[i] <- as.numeric(difftime(Daily$Date[i],Daily$Date[i-1]))
>}
>
>	[[alternative HTML version deleted]]
>
>______________________________________________
>R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>https://stat.ethz.ch/mailman/listinfo/r-help
>PLEASE do read the posting guide
>http://www.R-project.org/posting-guide.html
>and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list