rdatetimejoinposixctcolumn-types

Change order of classes in column


I have an date-time object like:

one <- structure(1678982734, class = c("POSIXt", "POSIXct"), tzone = "UTC"),
but when I try to join it with another dataframe where the classes are switched around, e.g,
two <- structure(1678982734, class = c("POSIXct", "POSIXt"), tzone = "UTC") the join is failing. How can I tell R to switch the order of the class vector that defines the column type?

For anyone running into the same issue I'm pasting my actual error message from my overlapping join in dplyr:

Error in `full_join()`:
! Can't join `x$timestamp` with `y$deploy_on_date` due to incompatible types.
ℹ `x$timestamp` is a <datetime<UTC>>.
ℹ `y$deploy_on_date` is a <POSIXt>.
Run `rlang::last_trace()` to see where the error occurred.

Solution

  • This is a bug with whatever created the object with class = c("POSIXt", "POSIXct"). As @MrFlick commented the 'class' vector should be in order of inheritance. 'POSIXct' inherits from 'POSIXt', not the other way around.

    In addition, 'POSIXt' is a "virtual" class, which means you can't create an object that is just class = "POSIXt". The only reason it exists is so 'POSIXct' and 'POSIXlt' objects can be operated on together (e.g. subtracting a 'POSIXct' object from a 'POSIXlt' object).

    Also as MrFlick said, you can reverse the class vector if it's malformed.

    check_posix_class <- function(x) {
        if (identical(class(x), c("POSIXt", "POSIXct"))) {
            class(x) <- rev(class(x))
        }
        return(x)
    }