2

I made a linear regression model by using the caret package with the code below

library(caret)
#Anscombe data is available on R
model_1<-train(
  form=y1~x1,
  data=anscombe,
  method='lm',
  trControl=trainControl(method='cv',number=3))

What I wanted to do is convert the model into a data frame using broom::tidy(model_1), but it throws an error

# Error: No tidy method for objects of class train

I think the problem is with the class of the caret's model, which is train() instead of lm(). Is there any way to tidy a train object? Or should I convert the train object into lm first?

Werner Hertzog
  • 2,002
  • 3
  • 24
  • 36

1 Answers1

1

This type of object is not currently supported by the broom package. See here: https://github.com/tidymodels/broom/issues/128

However, you could easily define your own tidy method by following the instructions here: https://www.tidymodels.org/learn/develop/broom/

Here is a minimal example:

library(caret)
library(broom)

tidy.train <- function(x, ...) {
  s <- summary(x, ...)
  out <- data.frame(term=row.names(s$coefficients),
                    estimate=s$coefficients[, "Estimate"],
                    std.error=s$coefficients[, "Std. Error"],
                    statistic=s$coefficients[, "t value"],
                    p.value=s$coefficients[, "Pr(>|t|)"])
  row.names(out) <- NULL
  out
}

model_1<-train(
  form=y1~x1,
  data=anscombe,
  method='lm',
  trControl=trainControl(method='cv',number=3))

tidy(model_1)
#>          term  estimate std.error statistic     p.value
#> 1 (Intercept) 3.0000909 1.1247468  2.667348 0.025734051
#> 2          x1 0.5000909 0.1179055  4.241455 0.002169629
Vincent
  • 15,809
  • 7
  • 37
  • 39
  • 1
    Thank you so much, Vincent! Btw, shouldn't it be `tidy.train(model_1)` ? – Matthew Farant Oct 25 '20 at 15:55
  • 1
    No, because if you run `class(model_1)`, you'll see that this is an object of class "train". So when you load `broom` and define a function called `tidy.train`, it will treat this function as a special "method" and apply it automatically to any object of class "train" when you just call `tidy`. Google "R S3 method" or read the `broom` tutorial that I linked to for more details. – Vincent Oct 25 '20 at 15:57