convert string back into object in r [closed]

两盒软妹~` 提交于 2019-11-28 14:35:54

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)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!