想知道是否有人成功地将R模型序列化和反序列化到Postgres数据库中。我尝试了不同的序列化JSON,原始e.t.c的方法,但均未成功。我正在使用RPostgreSQL软件包
伪代码,不起作用
# SERILIZE
fit <- lm(reading ~ ., mdata.sel)
pgcon <- mpr.getDBConnection()
on.exit(dbDisconnect(pgcon))
df <- data.frame(serialize(fit,NULL))
vector <- vector()
vector[1] <- "poly"
colnames(df) <- vector
dbWriteTable(pgcon, "ptest",
value = df , append = TRUE, row.names = FALSE)
# UNSERIALIZE
rows<-dbGetQuery(pgcon, "SELECT encode(poly::bytea,'escape') from ptest")
iter_model<-postgresqlUnescapeBytea(rows[["encode"]])
model<-unserialize(iter_model)
编辑
在How to write and read binary data with RPostgresql中找到了一个样本,该样本存储了模型,不幸的是,在反序列化检索到的对象时,它会损坏
con <- mpr.getDBConnection()
on.exit(dbDisconnect(pgcon))
dbGetQuery(con,"CREATE TABLE byteatable (name text NOT NULL, val bytea, PRIMARY KEY (name))")
ser <- serialize(fit,NULL,ascii=F)
postgresqlEscapeBytea(con, ser)
iq <- sprintf("INSERT INTO byteatable values('%s',E'%s');","name1", postgresqlEscapeBytea(con, ser))
dbGetQuery(con, iq)
rows<-dbGetQuery(con, "SELECT * from byteatable")
ser2<-postgresqlUnescapeBytea(rows[[2]])
unserialize(ser2) # CORRUPT
答案 0 :(得分:0)
序列化/反序列化为json,似乎可行
library(RPostgreSQL)
library(jsonlite)
mpr.test <- function(){
con <- mpr.getDBConnection()
on.exit(dbDisconnect(pgcon))
dbGetQuery(con,"CREATE TABLE public.strtable(poly character varying COLLATE pg_catalog.'default'')")
dbGetQuery(con, "DELETE FROM strtable")
md <- mpr.measurementdata_get("bbbb") #getting meaurement data
fit <- mpr.poly_calc(md) # lm model
iq <- sprintf("INSERT INTO strtable values('%s');", serializeJSON(fit, digits = 8, pretty = FALSE))
dbGetQuery(con, iq)
rows<-dbGetQuery(con, "SELECT * from strtable")
fit.db <- unserializeJSON(rows[[1]])
}