title: Serialize and deserialize model to Postgres in R
body: <p>Wondering if anyone has successfully managed to serialize and unserialize a R model into a Postgres database. I have tried different ways of serializeing JSON, raw e.t.c without success. I'm using the RPostgreSQL package</p>
  
  <p>Pseudo code, not working</p>
  
  <pre><code>  # SERILIZE
    fit &lt;- lm(reading ~ ., mdata.sel)
    pgcon &lt;- mpr.getDBConnection()
  
    on.exit(dbDisconnect(pgcon))
  
    df &lt;- data.frame(serialize(fit,NULL))
    vector &lt;- vector()
    vector[1] &lt;- "poly"
  
    colnames(df) &lt;- vector
  
    dbWriteTable(pgcon, "ptest",
                 value = df , append = TRUE, row.names = FALSE)
  
  
  
    # UNSERIALIZE    
    rows&lt;-dbGetQuery(pgcon, "SELECT encode(poly::bytea,'escape') from ptest")
  
    iter_model&lt;-postgresqlUnescapeBytea(rows[["encode"]])
  
    model&lt;-unserialize(iter_model)
  </code></pre>
  
  <p><strong>EDIT</strong></p>
  
  <p>Found a sample in <a href="https://stackoverflow.com/questions/37996319/how-to-write-and-read-binary-data-with-rpostgresql">How to write and read binary data with RPostgresql</a>, which stores the model, unfortunately when unserializing the retrieved object, it becomes corrupt</p>
  
  <pre><code>      con &lt;- mpr.getDBConnection()
  
        on.exit(dbDisconnect(pgcon))
  
        dbGetQuery(con,"CREATE TABLE byteatable (name text NOT NULL, val bytea, PRIMARY KEY (name))")
  
        ser &lt;- serialize(fit,NULL,ascii=F)
        postgresqlEscapeBytea(con, ser)
        iq &lt;- sprintf("INSERT INTO byteatable values('%s',E'%s');","name1", postgresqlEscapeBytea(con, ser))
        dbGetQuery(con, iq)
        rows&lt;-dbGetQuery(con, "SELECT * from byteatable")
        ser2&lt;-postgresqlUnescapeBytea(rows[[2]])
        unserialize(ser2) # CORRUPT
  </code></pre>