[R] Novice problems with write()

Liaw, Andy andy_liaw at merck.com
Wed Feb 4 03:39:33 CET 2004

> From: Bret Collier
> R-Users,
>          As a relatively new user of R, I have a quick (and probably 
> simple) question about using write().  I have a population 
> simulation that 
> I am running and I want to output a set of variables for each 
> run of the 
> simulation into a text file for use in another program.  
> However, whenever 
> I attempt to use write(), the only output that I am able to 
> get is the 
> final numbers from the simulation.
> for example:
> x <- 5
> for (i in 1:10){
>   z <- x+i
> print(z)
> write(z, "c:/test.txt")
> }

What you have done is write 6 through 15 to the file test.txt 10 times, each
with one number.  write() opens a file, write to it, and then close the
file, so if you do it in the loop, it would open the file 10 times, write
one number to it 10 times, and close the file 10 times.

You're probably looking for something like:

fout <- file("c:/test.txt", "w")
x <- 5
for (i in 1:10) {
  z <- x + i
  writeLines(paste(z, "\n"), fout)

Or simply:

write(5 + 1:10, file="c:/test.txt", ncol=1)


> In this simple case,  with print(z) I can see that z has what 
> I am looking 
> for, but all that is output for the write statement is 15;  
> While this is 
> simplified, it shows my problem.
> I searched the help files, and on the R website, but I could not find 
> anything addressing this.  I suspect that it is my lack of 
> knowledge and I 
> am missing something obvious (or should be using 
> write.table).  If anyone 
> could point me in the right direction I would appreciate it.
> Thanks,
> Bret Collier
> Univ. Arkansas
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://www.stat.math.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html

Notice:  This e-mail message, together with any attachments,...{{dropped}}

More information about the R-help mailing list