harrelfe / Hmisc

Harrell Miscellaneous
Other
204 stars 81 forks source link

label does not work on data.frame columns with class 'hms' #176

Open jackahall opened 10 months ago

jackahall commented 10 months ago

I'm trying to label a data.frame with one of the columns of the format 'hms', as follows:


library(Hmisc)

data <- data.frame(time = hms::hms(20, 20, 20))

label(data$time) <- "Time"

However, I get the following error when trying to view the data.frame in RStudio

Error in `as.character()`:
! Can't convert `x` <labelled> to <character>.
Run `rlang::last_trace()` to see where the error occurred.
couthcommander commented 10 months ago

Printing the column calls as.character which ends up calling hms:::as.character.hms. This then calls vctrs::vec_cast and so forth until the error occurs. In my opinion as.character.hms introduces the bug but because it offloads the work onto the "vctrs" package, I doubt there's an easy solution.

I'm not sure if the following approach will generalize, but it should work with the "hms" case. Define the following function:

as.character.labelled <- function(x) {
  class(x) <- setdiff(class(x), 'labelled')
  lab <- attr(x, 'label')
  ch <- as.character(x)
  label(ch) <- lab
  ch
}

I don't think it's a good solution for the Hmisc package - though perhaps @harrelfe may choose to implement a fix or can suggest a better approach. You might also try submitting an issue to "hms" (https://github.com/tidyverse/hms/issues), though they might say this is an "Hmisc" problem (in reality it's an R object oriented problem). Hope that helps.