[R] basic programming question

MMarques Power mmarques at inescporto.pt
Thu Apr 15 17:25:21 CEST 2004


Hello Randy,

Thursday, April 15, 2004, 4:08:14 PM, you wrote:

RZ> I am just starting to write some R functions (R 1.8 and Windows XP) and
RZ> got stuck as described below:
RZ> We have a bunch of time series data files, each is about 10,000 values.
RZ> There is a 12-line header in each one. I can read them and plot them
RZ> easily with R, but I want to make an automated system to read all the
RZ> files in a folder and have them appear as R objects that I can assemble in
RZ> different plots, or analyze together.
RZ> Perhaps this would be best done reading into a data table, where each row
RZ> is one of the files and each row extends for 10,000 columns? Or perhaps as
RZ> a matrix? I could use advice on that. My first notion, though, was just to
RZ> have them be individual files.
RZ> I started as follows:
RZ> # build a path from its parts:
RZ> p1="C:"
RZ> p2="Work-PSU"
RZ> p3="Lab-People-and-Projects"
RZ> p4="Dane"
RZ> p5="2004-04-06"
RZ> pt=file.path(p1,p2,p3,p4,p5,fsep="/")
RZ> #
RZ> lf<-list.files(pt)
RZ> ff="files"
RZ> sayfiles=paste(length(lf),ff,sep=" ")
RZ> #
RZ> # at this point if I type "sayfiles" I get "30 files" printed at the
RZ> console. OK, this is progress.
RZ> #
RZ> # Now I want to cycle through all the files and read in each one. The
RZ> # code here almost works, but I don't know how to do in R the simple task
RZ> # of substituting the read file name as the data object name.
RZ> #
RZ> d=dir(pt)
RZ> for (i in d){d[i]=scan(paste(pt,i,sep="/"),skip=12)} # this almost works
RZ> #
RZ> I know this is wrong, I just want to show my intention -- that is on each
RZ> iteration of the loop have a new R object made called d[i], the name of
RZ> the current file. This new object is then the result of the scan operation
RZ> on the file of that same name.


There are several aproaches to solve the problem

On that I use is to put each new file as a new object in the maisn env
of R.
something like this:

        zfil <- list.files(path, pattern = patt )
        for (ii in 1:length(zfil)  ) {
                f1path <- paste(path,"\\", zfil[ii], sep="")
                d1 <- scan(f1path, skip= 1,dec = dec1 , sep=";")
                assign(zfil[ii], d1, env= .GlobalEnv)
        }

so each time a new object is created with the name of the file.

Regarding the idea of putting all the data together a data frame would
be the answer...
Depending on the data it would be possible to make a matrix with some
thing like 100*100 and possibly concatenate the each matrix ...


-- 
Best regards,
 MMarques                            mailto:mmarques at power.inescn.pt




More information about the R-help mailing list