[R] Open file for reading and writing with APPEND

Henrik Bengtsson hb at biostat.ucsf.edu
Wed Sep 14 22:07:26 CEST 2011


See details on *argument* 'open' for file(), cf. help("file").

/Henrik

On Wed, Sep 14, 2011 at 12:38 PM, Noah Silverman <noahsilverman at ucla.edu> wrote:
> Hi,
>
> I want to keep a running file of some statistics generated by a running process.  Occasionally the process will be restarted.
>
> On  restart, I'd like to read the last line of the log file to set some variables to their last state, and then continue to append values to that same file.
>
> I can't seem to get the appending part to work.  I can read values form the file, but then upon the first write, the file is overwritten with the new values, so I lose my entire history.
>
> Any ideas?
>
> Here is what I'm using:
>
>
> =============================
> outfile <- file("logfile.csv", open="r")
> x <- readLines(outfile)
> lastLine <- x[length(x)]
> a <- as.numeric( strsplit(lastLine, " +")[[1]][1] )
> b <- as.numeric( strsplit(lastLine, " +")[[1]][2] )
> c <- as.numeric( strsplit(lastLine, " +")[[1]][3] )
> close(outfile)
>
> outfile <- file("logfile.csv", open="w")
>
>
> while(1){
>        # do a bunch of stuff
>        cat(a, b, c, sep=",", "\n",  file=outfile, append=TRUE)
>
> }
>
> =========================
>
>
> --
> Noah Silverman
> UCLA Department of Statistics
> 8117 Math Sciences Building #8208
> Los Angeles, CA 90095
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list