Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 205330

When creating Start and Endtimes within R, is there a way to make sure the days are grouped together?

$
0
0

I have a dataset that contains ID, Datetime and timediff. I grouped the ID and separated the Datetime into Starttime and Endtime, using this command:

data1 <- data %>% group_by(ID, col = rep(c('StartTime', 'EndTime'), length.out = n())) %>%
     mutate(id=row_number())%>%
     tidyr::pivot_wider(names_from = col,values_from = DateTimeUTC) %>%
     ungroup() %>%
     select(-id)

I then removed the last 'odd' row for each group by using: (I did this to avoid NA rows, the rows have to be even)

odd <- data1 %>%
   group_by(ss_ItemId) %>%
   slice(if(n()%% 2 == 0)row_number() else seq_len(n()-1))

I then took the difference of starttime and endtime using this:

diff<-odd %>%
   mutate at(vars(ends_with('Time')), lubridate::mdy_hms) %>%
   mutate(diff = difftime(EndTime, StartTime, units = "secs"))

Is there a way to also group the start and endtimes by the day so that the durations wont be 'off'?: (For instance, keep everything from 12/17 together, and keep everything from 12/18 together while still grouping by ID?)

                    ID              Starttime                 Endtime                timediff

                    A               12/17/2019 9:29:24 PM    12/17/2019 9:29:25 PM   1 
                    A               12/17/2019 9:29:26 PM    12/18/2019 4:50:01 PM   69635

I would like the ouput to be:

                    ID              Starttime                Endtime                  timediff


                    A               12/17/2019 9:29:24 PM    12/17/2019 9:29:25 PM    1
                    A               12/17/2019 9:29:26 PM       
                    A               12/18/2019 4:50:01 PM

Any suggestion is appreciated. I will continue to research. Thank you


Viewing all articles
Browse latest Browse all 205330

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>