[R] repeat write.table with the same code many times

Joshua Wiley jwiley.psych at gmail.com
Tue Nov 30 17:48:10 CET 2010


Hi Laura,

I'm a little weak on my use of connections, but I wonder if something
like this would not be a better option.  As I understand it, using
write.table() with append = TRUE is a slow way to many lines to a
file.


## create a writable connection to a file
gt <- file("bootstrap_results.txt", open = "wt")
## cat rnorm(10) (with the line break "\n" added) 10 times to the connectioned
for(i in 1:10) cat(c(rnorm(10), "\n"), file = gt)
## close connection when done
close(gt)

HTH,

Josh

On Tue, Nov 30, 2010 at 6:57 AM, Laura Bonnett <l.j.bonnett at gmail.com> wrote:
> Dear all,
>
> I am using R version 2.9.2 in Windows.
>
> I would like to output the results of a function I have written to a .txt
> file.  I know that I can do this by using the code
> write.table(boothd(10),"boothd10.txt",sep="\t",append=TRUE) etc.  However, I
> would like to bootstrap my function 'boothd' several times and get each
> vector of results as a new line in my text file.  Is there a way to do this?
>
> I usually just set the code up to do bootstrapping around the function (i.e.
> I perform the replications within the function and output a matrix of
> results).  However in the case of 'boothd' I am dealing with rare events and
> so sometimes I get an empty vector as output which makes mathematical
> sense.  Unfortunately this casues the bootstrapping code to crash.
>
> I'm hoping that writing the results out line by line will remove this
> problem.  I have tried rep(write.table(...),15) say but because of the
> occasional null vector the table is not written.
>
> Thank you for any help you can give.
>
> By the way,
> write.table(boothd(10),"boothd10.txt",sep="\t",append=TRUE)
> write.table(boothd(10),"boothd10.txt",sep="\t",append=TRUE)
> write.table(boothd(10),"boothd10.txt",sep="\t",append=TRUE)
> write.table(boothd(10),"boothd10.txt",sep="\t",append=TRUE)
> write.table(boothd(10),"boothd10.txt",sep="\t",append=TRUE) etc works but if
> I want to look at 1000 replications this is very time consuming!
>
> Thanks,
> Laura
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list