简体   繁体   中英

Create start and end time column from a single datetime column in R

I am wanting to create a startime and endtime column from my current datetime column in R. My data has been grouped by ID.

Here is the data:

                    ID                    DATETIMEUTC


                    A                     12/17/2019 9:46:04 PM
                    A                     12/17/2019 9:46:05 PM                                                
                    A                     12/18/2019 2:34:56 AM
                    A                     12/18/2019 2:34:58 AM 

I am wanting this outcome:

           ID                   StartTime                       EndTime

           A                    12/17/2019 9:46:04 PM           12/17/2019 9:46:05 PM
           A                    12/18/2019 2:34:56 AM           12/18/2019 2:34:58 AM

Here is the code that I am writing to try and achieve this:

            library(dplyr)

            df %>%
            group_by(id) %>%
            mutate(start=date, stop=lead(start, default=end[1]))

This command is not yielding the desired result. I am still researching this. Any suggestions is greatly appreciated!

Tanisha Hudson

We can create a new column with alternate values of c('StartTime', 'EndTime') , group by ID , create a unique row number for each group and spread the data in wide format.

library(dplyr)
df %>%
  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)

# A tibble: 2 x 3
#  ID    StartTime             EndTime              
#  <fct> <fct>                 <fct>                
#1 A     12/17/2019 9:46:04 PM 12/17/2019 9:46:05 PM
#2 A     12/18/2019 2:34:56 AM 12/18/2019 2:34:58 AM

data

df <- structure(list(ID = structure(c(1L, 1L, 1L, 1L), .Label = "A", 
class = "factor"), DATETIMEUTC = structure(1:4, .Label = c("12/17/2019 9:46:04 PM", 
"12/17/2019 9:46:05 PM", "12/18/2019 2:34:56 AM", "12/18/2019 2:34:58 AM"
), class = "factor")), class = "data.frame", row.names = c(NA, -4L))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM