Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write lines of text to a file in R

Tags:

file-io

r

In the R scripting language, how do I write lines of text, e.g., the following two lines

Hello World 

to a file named "output.txt"?

like image 284
amarillion Avatar asked Mar 18 '10 13:03

amarillion


People also ask

How do you write lines in R?

R base function writeLines() is used to write the sequence of multiple lines to the text file. This method accepts Vector with the lines you would like to write or string. To create a vector use c() function. The option of writeLines() is roughly ten times faster then the sink() and cat() methods explained below.

How do you write an output to a text file?

Steps for writing to text files First, open the text file for writing (or append) using the open() function. Second, write to the text file using the write() or writelines() method. Third, close the file using the close() method.

Which function writes appends data to a file in R?

By default, the write. csv() function overwrites entire file content. In order to append the data to a CSV File, use the write. table() method instead and set the parameter, append = TRUE.


2 Answers

fileConn<-file("output.txt") writeLines(c("Hello","World"), fileConn) close(fileConn) 
like image 153
Mark Avatar answered Oct 02 '22 13:10

Mark


Actually you can do it with sink():

sink("outfile.txt") cat("hello") cat("\n") cat("world") sink() 

hence do:

file.show("outfile.txt") # hello # world 
like image 38
aL3xa Avatar answered Oct 02 '22 13:10

aL3xa