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"?
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.
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.
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.
fileConn<-file("output.txt") writeLines(c("Hello","World"), fileConn) close(fileConn)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With