[R] writing multiple lines to a file

arun smartpink111 at yahoo.com
Wed Jul 17 19:32:37 CEST 2013


Hi,
No problem.

You could try:

printer = file("out.txt","w")
 writeLines("This is line.",con=printer,sep=" ")
 writeLines("The same line.",con=printer)
 close(printer)

#or
cat(sprintf("This is line %d. ",1),file="out.txt",append=TRUE)
cat("The same line.",file="out.txt",append=TRUE)

A.K.

Thank you very much, I just have one more simple question. It worked 
with writing "w" when opening the file. However another problem 
occoured, When I wrote \n, it went two lines down, so I had to do this, 
witout \n 

printer = file("out.txt","w") 
write(sprintf("This is line %d.",1),printer,append=T) 
write("This is line 2.",printer,append=T) 
close(printer) 


However, sometimes, I do not want to start on the new line, 
it depends on the situation. That is I may write something to a file. 
And then I want to add to the same line a new string: 
" The same line." Like this. 

printer = file("out.txt","w") 
write(sprintf("This is line %d.",1),printer,append=T) 
write(" The same line.",printer,append=T) 
close(printer) 

But the output is: 
This is line 1. 
 The same line. 


How can I make it stop going to the new line automatically. 


----- Original Message -----
From: arun <smartpink111 at yahoo.com>
To: R help <r-help at r-project.org>
Cc: 
Sent: Tuesday, July 16, 2013 10:53 PM
Subject: Re: writing multiple lines to a file

HI,
May be this helps:
printer1<- file("out1.txt","w")
write(sprintf("This is line %d.\n",1),printer1,append=TRUE) 
write("This is line 2",printer1,append=TRUE)
close(printer1)

#or


 printer1<- file("out1.txt","w")
writeLines("This is line",con=printer1,sep="\n")
writeLines("This is line 2",con=printer1)
 close(printer1)
A.K.


Hello, I am trying to wrote multiple lines to a file, but I only seem to be able to write the last line. 

printer = file("out.txt") 
write(sprintf("This is line %d.\n",1),printer,append=T) 
write("This is line 2.",printer,append=T) 
close(printer) 

How can I fix this? I would like to be able to do this in a for-loop with hundreds of elements.



More information about the R-help mailing list