[R] Reading and writing to S-like databases

Martin Maechler maechler at stat.math.ethz.ch
Mon Oct 1 14:33:40 CEST 2001


>>>>> "DavidB" == David Brahm <a215020 at agate.fmr.com> writes:
    DavidB> I asked:
    >> In S-Plus, I build databases of many large objects.  In any given
    >> analysis, I only need a few of those objects, but attach'ing the
    >> whole database is fine since objects are only read as needed.  How
    >> can I do the same thing in R, without reading the entire database?

    DavidB> Responses were generally in 2 categories: 1) Use an external
    DavidB> SQL database (fine for dataframes, but not flexible enough), 2)
    DavidB> Use autoload() or delay() (thanks to Agustin Lobo & Ray
    DavidB> Brownrigg!).  Here's what I came up with from the second
    DavidB> approach.

>> ##### Code: #####
>> "%&%" <- function(a, b) paste(a, b, sep="")

>> g.save.data <- function(dir, pos=2) {
>>   for (i in dir %&% c("", "/data", "/R")) if (!file.exists(i)) dir.create(i)
>>   obj <- objects(pos, all.names=T)
>>   for (i in obj) save(list=i, file=dir %&% "/data/" %&% i %&% ".RData")
>>   code <- obj %&% " <- delay({data(\"" %&% obj %&% "\"); " %&% obj %&% "})"
>>   cat(code, file=dir %&% "/R/" %&% basename(dir), sep="\n")
>> }

Just a ``didactical'' comment on the code above :  The
   >> for (i in dir %&% c("", "/data", "/R")) 
   >>	  if(!file.exists(i)) dir.create(i)
part (using your own "%&%" function) 
is probably better written as something like
   
    for (d in dir) { 
	i <- file.path(d,"data","R")
        if (!file.exists(i)) dir.create(i)
    }

a version which is platform independent {i.e. should work on all flavors of
Unix, Windows, and MacOS} since it does not rely on explicit pasting of
strings for path creation.
And the same of course applies to the same thing in subsequent lines of
your g.save.data() function.

>> g.attach <- function(dir) library(basename(dir), lib.loc=dirname(dir), char=T)

>> 
>> ##### Example: #####
>> attach(NULL, name="newdata")    # Create some data in a new environment
>> assign("x1",  1:10, 2)
>> assign("x2", 11:20, 2)
>> g.save.data("/tmp/newdata")     # Save that environment's contents to a pkg
>> detach(2)
>> g.attach("/tmp/newdata")        # Open the pkg and see the data!
>> 

    DavidB> 		-- David Brahm (a215020 at agate.fmr.com)

Martin Maechler <maechler at stat.math.ethz.ch>	http://stat.ethz.ch/~maechler/
Seminar fuer Statistik, ETH-Zentrum  LEO D10	Leonhardstr. 27
ETH (Federal Inst. Technology)	8092 Zurich	SWITZERLAND
phone: x-41-1-632-3408		fax: ...-1228			<><
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list