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

James W. MacDonald jmacdon at med.umich.edu
Tue Nov 30 17:46:51 CET 2010


Hi Laura,

On 11/30/2010 9:57 AM, Laura Bonnett 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!

write.table() has a lot of added niceties that you don't need. There are 
two lower-level functions that could do what you want. First you could 
use cat(), along with file(). Something like

con <- file("thefile.txt", "w")
for(i in my_bootstraps){
   do_stuff_here
   cat(results_vector, "\n", sep = "\t", file = con)
}
close(con)

If you want an empty line for the empty vector, you can use an if() 
statement to cat() something else to the file at that point.

You could also use writeLines(), but that is likely too low-level for 
your needs.

Best,

Jim


>
> 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.

-- 
James W. MacDonald, M.S.
Biostatistician
Douglas Lab
University of Michigan
Department of Human Genetics
5912 Buhl
1241 E. Catherine St.
Ann Arbor MI 48109-5618
734-615-7826
**********************************************************
Electronic Mail is not secure, may not be read every day, and should not be used for urgent or sensitive issues 



More information about the R-help mailing list