I frequently create nonparametric statistics (loess, kernel densities, etc) on data I pull out of a relational database. To make data management easier I would like to store
For sqlite
(and possibly others):
CREATE TABLE data (blob BLOB);
Now in R
:
RSQLite::dbGetQuery(db.conn, 'INSERT INTO data VALUES (:blob)', params = list(blob = list(serialize(some_object)))
Note the list
wrapper around some_object
. The output of serialize
is a raw vector. Without list
, the INSERT statement would be executed for each vector element. Wrapping it in a list allows RSQLite::dbGetQuery
to see it as one element.
To get the object back from the database:
some_object <- unserialize(RSQLite::dbGetQuery(db.conn, 'SELECT blob FROM data LIMIT 1')$blob[[1]])
What happens here is you take the field blob
(which is a list since RSQLite doesn't know how many rows will be returned by the query). Since LIMIT 1
assures only 1 row is returned, we take it with [[1]]
, which is the original raw vector. Then you need to unserialize
the raw vector to get your object.