Search code examples
rparsingglmlm

R, Is there a function for deparsing and (re)parsing any regression output for lm/glm/semgented models?


Is there an R package/class/code that will deparse the output object from lm or glm into text (or JSON/XML/Other MarkUp) and can also parse it back into an object with the same structure as the original (i.e. so code can query the new object in the same way as the original)?

To complicate matters, I want to be able to do the same with output from the segmented package. So I am looking for something that can read the syntax of any parsed list, including the attr, into the originally structured list object with attr. But a solution to the single lm would be a good starting point.

So far I have tried:

  1. toJSON //does not support R type 6)//
  2. toString then as.list //gives a list with all in one item and escape symbols prevent parsing//
  3. deparse(str(summary(OUTPUT))) //No error but returns NULL//
  4. deparse(OUTPUT) then as.list //gives a list with one item per top level but sublevels are just in a string.
  5. deparse (OUTPUT) then parse directly //Error, must be a string or connection//
  6. passing the string output to a new structure() object //Same Result as 4 except not recognised as list by rstudio//
  7. Exporting the summary metrics to a data frame and then to JSON //Keeps the coeffs but loses other information//

I wish to avoid having to make any assumptions about the original structure or number of terms in the formula (so other regression models can be used) which means code to scan the deparsed lm model will need to be quite subtle.


Solution

  • As @AEF mentions in their comment, you might be looking for serialization with saveRDS(). If you specifically need a text format rather than a binary one, you can use ascii = TRUE.

    fit0 <- lm(mpg ~ wt, data = mtcars)
    saveRDS(fit0, "model.rds", ascii = TRUE)
    fit1 <- readRDS("model.rds")
    
    predict(fit0, data.frame(wt = 3))
    #>        1 
    #> 21.25171
    predict(fit1, data.frame(wt = 3))
    #>        1 
    #> 21.25171