Search code examples
rdatetimeposixct

How to merge `Date` and `times` columns to obtain a single column in `POSIXct format`


I have the following dataframe:

>dput(df)
 structure(list(Date = structure(c(18724, 18724, 18725, 18725, 18726, 18726, 18726, 18731, 18731, 
                                   18731), class = "Date"), 
                Time = structure(c(0.490277777777778, 0.490277777777778, 0.552083333333333, 
                                    0.552083333333333, 0.461805555555556, 0.461805555555556, 
                                    0.461805555555556, 0.647916666666667, 0.647916666666667,
                                    0.647916666666667), format = "h:m:s", class = "times"), 
                Date.1 = structure(c(18725, 18725, 18726, 18726, 18727, 18727, 18727, NA, NA, NA), 
                                     class = "Date"), 
                Time.1 = structure(c(0.754861111111111, 0.754861111111111, 0.9375, 0.9375, 
                                      0.472222222222222, 0.472222222222222, 0.472222222222222, NA, 
                                      NA, NA), format = "h:m:s", class = "times")), row.names = c(NA,                                                                        
                                      10L), class = "data.frame")

I would like to merge Date and Time columns (Date with Time, and Date.1 with Time.1) to obtain a single column in POSIXct format (i.e. one column from Date - Time columns, and another from Date.1 - Time.1 columns).


Solution

  • library(data.table)
    setDT(df)
    df[, datetime := as.POSIXct( as.ITime(Time), as.IDate(Date))]
    df[, datetime.1 := as.POSIXct( as.ITime(Time.1), as.IDate(Date.1))]
    #          Date      Time     Date.1    Time.1            datetime          datetime.1
    # 1: 2021-04-07 0.4902778 2021-04-08 0.7548611 2021-04-07 11:46:00 2021-04-08 18:06:59
    # 2: 2021-04-07 0.4902778 2021-04-08 0.7548611 2021-04-07 11:46:00 2021-04-08 18:06:59
    # 3: 2021-04-08 0.5520833 2021-04-09 0.9375000 2021-04-08 13:14:59 2021-04-09 22:30:00
    # 4: 2021-04-08 0.5520833 2021-04-09 0.9375000 2021-04-08 13:14:59 2021-04-09 22:30:00
    # 5: 2021-04-09 0.4618056 2021-04-10 0.4722222 2021-04-09 11:05:00 2021-04-10 11:19:59
    # 6: 2021-04-09 0.4618056 2021-04-10 0.4722222 2021-04-09 11:05:00 2021-04-10 11:19:59
    # 7: 2021-04-09 0.4618056 2021-04-10 0.4722222 2021-04-09 11:05:00 2021-04-10 11:19:59
    # 8: 2021-04-14 0.6479167       <NA>        NA 2021-04-14 15:33:00                <NA>
    # 9: 2021-04-14 0.6479167       <NA>        NA 2021-04-14 15:33:00                <NA>
    #10: 2021-04-14 0.6479167       <NA>        NA 2021-04-14 15:33:00                <NA>