Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading