[R] group consecutive dates in a row

2023-08-07 Thread Stefano Sofia
Dear R users, I have a data frame with a single column of POSIXct elements, like mydf <- data.frame(data_POSIX=as.POSIXct(c("2012-02-05", "2012-02-06", "2012-02-07", "2012-02-13", "2012-02-21"), format = "%Y-%m-%d", tz="Etc/GMT-1")) I need to transform it in a two-columns data frame where I c

Re: [R] group consecutive dates in a row

2023-08-07 Thread Ben Bolker
rle(as.numeric(diff(mydf$data_POSIX))) should get you started, I think? On 2023-08-07 12:41 p.m., Stefano Sofia wrote: Dear R users, I have a data frame with a single column of POSIXct elements, like mydf <- data.frame(data_POSIX=as.POSIXct(c("2012-02-05", "2012-02-06", "2012-02-07", "2012-0

Re: [R] group consecutive dates in a row

2023-08-07 Thread Bert Gunter
Here is another way to obtain the day differences that is the argument of rle() . It is perhaps more reliable in that it uses methods for class POSIXct rather than depending on the underlying class structure and conversion via as.numeric. In theory, the methods won't change or any changes will be d

Re: [R] group consecutive dates in a row

2023-08-07 Thread Gabor Grothendieck
It is best to use Date, rather than POSIXct, class if there are no times. Use the cumsum expression shown to group the dates and then summarize each group. We assume that the dates are already sorted in ascending order. library(dplyr) mydf <- data.frame(date = as.Date(c("2012-02-05", "2012-

[R] Merge with closest (not equal) time stamps

2023-08-07 Thread Naresh Gurbuxani
I have two dataframes, each with a column for timestamp. I want to merge the two dataframes such that each row from first dataframe is matched with the row in the second dataframe with most recent but preceding timestamp. Here is an example. option.trades <- data.frame(timestamp = as.POSIXct(c(