I'm trying to use modelsummary to report a test. A sample of what test I use is on the following lines:
library(stats)
library(modelsummary)
set.seed(10)
ts1 <- rnorm(200, mean = 10, sd = 3) %>% ts()
test <- Box.test(ts1,lag = 5, type = "Ljung-Box", fitdf = 2)
class(test)
After generating the test, I try to create very simple functions called tidy.htest
and glance.htest
as printed below:
tidy.htest <- function(s, ...) {
ret <- data.frame(
term = "Test Statistic",
estimate = s$statistic[[1]],
p.value = s$p.value)
ret
}
glance.htest <- function(s, ...) {
ret <- data.frame(
DF = s$parameter[[1]]
)
ret
}
and then I run
modelsummary(test)
But I get the following error:
Error: `modelsummary could not extract the required information from a model of class "htest". The
package tried a sequence of 2 helper functions to extract estimates:
parameters::parameters(model)
broom::tidy(model)
To draw a table, one of these commands must return a `data.frame` with a column named "term". The
`modelsummary` website explains how to summarize unsupported models or add support for new models
yourself: https://vincentarelbundock.github.io/modelsummary/articles/modelsummary.html
These errors messages were generated during extraction:
`parameters::parameters(model)` did not return a data.frame with a `term` column.
`broom::tidy(model)` did not return a data.frame with a `term` column.
I'm sorry if there is something obvious that I didn't get, but it seems that the problem is that there is no "term" column but tidy.htest
does generate a "term" column.
I'd really appreciate if someone could help. Thanks in advance!
Background: modelsummary
uses the broom
or parameters
packages to extract coefficients from model objects. The problem is that both of these packages have methods to handle htest
objects, but that neither returns a "standard" object. In particular, we do not get a term
column, which modelsummary
requires.
When you tried to define your own methods, there's a conflict which gets resolved in favor of the built-in broom
method.
One workaround would be to change the class of your object and define new methods against that class:
library(stats)
library(modelsummary)
set.seed(10)
ts1 <- rnorm(200, mean = 10, sd = 3) |> ts()
test <- Box.test(ts1,lag = 5, type = "Ljung-Box", fitdf = 2)
tidy.custom <- function(s, ...) {
ret <- data.frame(
term = "Test Statistic",
estimate = s$statistic[[1]],
p.value = s$p.value)
ret
}
glance.custom <- function(s, ...) {
ret <- data.frame(
DF = s$parameter[[1]]
)
ret
}
class(test) <- "custom"
modelsummary(test, statistic = "p.value")
+----------------+---------+
| | (1) |
+================+=========+
| Test Statistic | 3.971 |
+----------------+---------+
| | (0.265) |
+----------------+---------+