0

I'm doing an ML course and I'm trying to save a trained model from the course's workspace so that I can reproduce everything on my own computer. So far I've just used dput() on a variable and it has worked perfectly. Now I'm trying to do the same on a model object, which is a decision tree. class(model) yields "_rpart" "model_fit"

When I run dput(model) it all seems to work but when I try to run the copied code I get the following error message: Error in missing_arg() : could not find function "missing_arg"

I can see that the code for the object contains missing_arg() several places like so:

structure(list(lvl = c("yes", "no"), spec = structure(list(args = list(
    cost_complexity = ~1e-10, tree_depth = ~15L, min_n = ~NULL), 
    eng_args = structure(list(), names = character(0), class = c("quosures", 
    "list")), mode = "classification", user_specified_mode = TRUE, 
    method = list(libs = "rpart", fit = list(interface = "formula", 
        protect = c("formula", "data", "weights"), func = c(pkg = "rpart", 
        fun = "rpart"), defaults = list(), args = list(formula = missing_arg(), 
            data = missing_arg(), weights = missing_arg(), cp = ~1e-10, 
            maxdepth = ~15L)), pred = list(class = list(pre = NULL, 
        post = NULL, func = c(fun = "predict"), args = list(object = object$fit, 
            newdata = new_data, type = "class")), prob = list(
        pre = NULL, post = function (x, object) 

Is there a way to save this model using dput(), or something similar, so that I can reproduce all the work on my own computer?

I'm sorry for not having a better reprex...

Economist
  • 173
  • 8
  • In this case I'm trying to save from the course's workspace so unfortunately I don't have access to saving to a file and then download it to my computer. The only way I've figured out has been to run dput() and then copy the output from the screen. Unfortunately this doesn't seem to work with a trained model. It's the same issue if I run dput() on a model I've trained myself on my own computer and then try to run it after saving the output to a file. Was hoping there was a away to do this but maybe there isn't. – Economist Mar 11 '23 at 22:50
  • 1
    It's probably helpful to keep in mind that `dput()` stores only plain text, but most models can't be presented well or correctly as plain text. To save a model to use in a different session, you would need to store it as a binary object, like `.rds`. – Julia Silge Mar 15 '23 at 03:29

1 Answers1

3

I would always prefer .rds to store any R object compared to dput() (which stores an ASCII text representation of the object). Try

readr::write_rds(model)
dufei
  • 2,166
  • 1
  • 7
  • 18
  • 1
    For OP, you can also use `save(“xyz.Rdata”)` to save all objects in your environment. Typically, @dufei answer is better, especially if you just want to save one object – mfg3z0 Mar 11 '23 at 17:57
  • 1
    For a base R solution, use `saveRDS()` – mfg3z0 Mar 11 '23 at 17:58