0

In R, I get the content of a binary file as a string (because of design issues, I can't access the file directly).

This file was originally an lm model.

How do I convert that string back into the lm model?

Thanks

elfersi
  • 121
  • 2
  • 13

1 Answers1

0

I'm assuming you used base::dput() according to the following example (based on this answer):

# Generate some model over some data
data <- sample(1:100, 30)
df <- data.frame(x = data, y = 2 * data + 20)
model <- lm(y ~ x, df)

# Assuming this is what you did you have the model structure inside model.R
dput(model, control = c("quoteExpressions", "showAttributes"), file = "model.R")


# ----- This is where you are, I presume -----
# So you can copy the content of model.R here (attention to the single quotes)
mstr <- '...'

# Execute the content of mstr as a piece of code (loading the model)
model1 <- eval(parse(text = mstr))

# Parse the formulas
model1$terms <- terms.formula(model1$terms)


# ----- Test it -----
# New data
df1 <- data.frame(x = 101:110)

pred <- as.integer(predict(model, df1))
pred1 <- as.integer(predict(model1, df1))

identical(pred, pred1)
# [1] TRUE


model
# 
# Call:
# lm(formula = y ~ x, data = df)
# 
# Coefficients:
# (Intercept)            x  
#          20            2  
# 

model1
# 
# Call:
# lm(formula = y ~ x, data = df)
# 
# Coefficients:
# (Intercept)            x  
#          20            2  

# Check summary too (you'll see some minor differences)
# summary(model)
# summary(model1)
vhcandido
  • 344
  • 2
  • 5
  • what if initially saveRDS was used instead of dput? – elfersi Aug 24 '18 at 22:52
  • @elfersi then you wouldn't be able to type it as a string, afaik – vhcandido Aug 29 '18 at 14:27
  • @李哲源 because that's what the author asked for, a way of loading the model as a string placed in the source code, without having to load it from disk. – vhcandido Aug 29 '18 at 14:31
  • if I have a list object of lm models (instead of a single lm model object), do I have to dput each lm model separately? Or, is there a way to dput them all as a single file and then convert back each of them to a lm model? – elfersi Aug 29 '18 at 22:53
  • @elfersi If you'll be able to access this file later, then you can save them all in one file with `save()`, or each one in a separate file with `saveRDS()`. But if string is necessary, as in the original post, then you can try to save them together with `dput(list(model1, model2), ...)`. However it's already going to be messy enough without binding them together, so I'd dput each one of them in its own string. – vhcandido Aug 30 '18 at 03:39