【问题标题】:Convert raw vector to R object将原始向量转换为 R 对象
【发布时间】:2016-07-07 07:05:48
【问题描述】:

如何在不写入磁盘的情况下将原始向量转换回 R 对象?我想读取 base64 数据流并将其转换为它的 R 对象表示。这是一个示例 - 我如何从原始向量中取回 lm 对象?

## some rdata -- writes to temp file!
mod <- lm(mpg ~ cyl, data=mtcars)
f1 <- tempfile()
save(mod, file=f1, compress="bzip2")

library(base64enc)
r1 <- readBin(f1, "raw", n=file.info(f1)[1, "size"])
r2 <- base64decode(base64encode(file(f1, "rb")))  # emulate input base64
identical(r1, r2)

## I can get mod back by writing to file and loading, but how to just
## load from a raw vector?
rm(mod)  # get rid of mod
f2 <- tempfile()
writeBin(r2, f2)
load(f2)  # mod is back

【问题讨论】:

    标签: r base64 type-conversion


    【解决方案1】:

    在我的 RcppRedis 包中,我使用 RApiSerialize 包(它基于最初从 Rhpc 包中借用的基本 R 代码)进行这些转换:

    R> mod <- lm(mpg ~ cyl, data=mtcars)     # your example
    R>
    R> library(RApiSerialize)
    R> modraw <- serializeToRaw(mod)         # serialized
    R> str(modraw)                           # really just a raw vector now
     raw [1:6819] 58 0a 00 00 ...
    R> 
    

    所以此时你可以对原始向量做任何你想做的事情。将其写入磁盘,将其写入数据库(就像我们使用 RcppRedis 所做的那样),......

    但重要的是,您还可以恢复您的模型:

    R> summary( unserializeFromRaw(modraw) )
    
    Call:
    lm(formula = mpg ~ cyl, data = mtcars)
    
    Residuals:
       Min     1Q Median     3Q    Max 
    -4.981 -2.119  0.222  1.072  7.519 
    
    Coefficients:
                Estimate Std. Error t value Pr(>|t|)    
    (Intercept)   37.885      2.074   18.27  < 2e-16 ***
    cyl           -2.876      0.322   -8.92  6.1e-10 ***
    ---
    Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
    
    Residual standard error: 3.21 on 30 degrees of freedom
    Multiple R-squared:  0.726, Adjusted R-squared:  0.717 
    F-statistic: 79.6 on 1 and 30 DF,  p-value: 6.11e-10
    
    R> 
    

    【讨论】:

    • 我猜可以压缩 after 序列化和解压缩 before 反序列化。但是您可能想查看saveRDS()readRDS(),它们优于save()load() 并且已经使用压缩,除非您将其关闭。是的,整个主题有点令人困惑,但*RDS() 函数以及我上面的(反)序列化函数有助于很大一部分。这不仅仅是base64 ...
    【解决方案2】:

    对于 R 级访问,请使用 unserialize(serialize(mod, NULL)) 从 R 对象到原始向量并返回。

    【讨论】:

      猜你喜欢
      • 2021-06-02
      • 2017-04-02
      • 2013-01-12
      • 1970-01-01
      • 2011-05-01
      • 1970-01-01
      • 2010-09-24
      • 2015-12-19
      相关资源
      最近更新 更多