将字符串转换回r中的对象 [英] convert string back into object in r

查看:316
本文介绍了将字符串转换回r中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在R中,我以字符串形式获取二进制文件的内容(由于设计问题,我无法直接访问该文件).

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

此文件最初是lm模型.

This file was originally an lm model.

如何将字符串转换回lm模型?

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

谢谢

推荐答案

我假设您根据以下示例使用了base::dput()(基于

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)

这篇关于将字符串转换回r中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆