dmurdoch / tables

Formula-Driven Table Generation
https://dmurdoch.github.io/tables/
13 stars 2 forks source link

Using `All()` with a labelled variable fails #17

Closed etiennebacher closed 1 year ago

etiennebacher commented 1 year ago

Hello, thanks for this amazing package!

I have a problem with tables::tabular() when I use All() in the formula and there's a least one labelled variable in the data:

library(tables)
packageVersion("tables")
#> [1] '0.9.21'

dat <- mtcars[, 1, drop = FALSE]
tabular(All(dat) ~ mean, dat)
#>           
#>      mean 
#>  mpg 20.09

dat$mpg <- haven::labelled(dat$mpg, label = "miles per gallon")
tabular(All(dat) ~ mean, dat)
#> Error in switch(deparse(e[[1]]), `*` = c(factors(e[[2]]), factors(e[[3]])), : EXPR must be a length 1 vector
dmurdoch commented 1 year ago

I can confirm the issue. The problem is that tabular isn't recognizing dat$mpg as a vector of doubles, because haven put class "labelled" on it. I'm not a haven user, so I don't know the recommended way to remove that class, but you will need to do that to get it to work. (I tried zap_label(), but it doesn't work. It leaves the class there. Bug? unclass() works, but leaves the label attribute. Maybe unclass(zap_label())?)

If you read the haven::labelled help page, you'll see that tabular is not alone in having trouble dealing with labelled objects.

dmurdoch commented 1 year ago

Sorry, this really is a bug in tables. It doesn't have much to do with haven: the problem is that deparse(e[[1]]) was two lines long, and the switch() function wants something that's only one line long. This is easy to fix; a bug fix will soon appear on Github.

etiennebacher commented 1 year ago

Great! FYI this will be useful for modelsummary users because there's an option to automatically replace variable names by their labels but it doesn't work with All() due to this issue.

dmurdoch commented 1 year ago

I've now merged the fix into the main. Could you confirm that things are working for you?

etiennebacher commented 1 year ago

Yup, all good, thanks for the quick fix