Write lines of text to a file in R

File IoR

File Io Problem Overview


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"?

File Io Solutions


Solution 1 - File Io

fileConn<-file("output.txt")
writeLines(c("Hello","World"), fileConn)
close(fileConn)

Solution 2 - File Io

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

Solution 3 - File Io

I would use the cat() command as in this example:

> cat("Hello",file="outfile.txt",sep="\n")
> cat("World",file="outfile.txt",append=TRUE)

You can then view the results from with R with

> file.show("outfile.txt")
hello
world

Solution 4 - File Io

What's about a simple writeLines()?

txt <- "Hallo\nWorld"
writeLines(txt, "outfile.txt")

or

txt <- c("Hallo", "World")
writeLines(txt, "outfile.txt")

Solution 5 - File Io

I suggest:

writeLines(c("Hello","World"), "output.txt")

It is shorter and more direct than the current accepted answer. It is not necessary to do:

fileConn<-file("output.txt")
# writeLines command using fileConn connection
close(fileConn)

Because the documentation for writeLines() says:

> If the con is a character string, the function calls file to obtain > a file connection which is opened for the duration of the function > call.

# default settings for writeLines(): sep = "\n", useBytes = FALSE
# so: sep = "" would join all together e.g.

Solution 6 - File Io

You could do that in a single statement

cat("hello","world",file="output.txt",sep="\n",append=TRUE)

Solution 7 - File Io

Short ways to write lines of text to a file in R could be realised with cat or writeLines as already shown in many answers. Some of the shortest possibilities might be:

cat("Hello\nWorld", file="output.txt")
writeLines("Hello\nWorld", "output.txt")

In case you don't like the "\n" you could also use the following style:

cat("Hello
World", file="output.txt")

writeLines("Hello
World", "output.txt")

While writeLines adds a newline at the end of the file what is not the case for cat. This behaviour could be adjusted by:

writeLines("Hello\nWorld", "output.txt", sep="") #No newline at end of file
cat("Hello\nWorld\n", file="output.txt") #Newline at end of file
cat("Hello\nWorld", file="output.txt", sep="\n") #Newline at end of file

But main difference is that cat uses R objects and writeLines a character vector as argument. So writing out e.g. the numbers 1:10 needs to be casted for writeLines while it can be used as it is in cat:

cat(1:10)
writeLines(as.character(1:10))

and cat can take many objects but writeLines only one vector:

cat("Hello", "World", sep="\n")
writeLines(c("Hello", "World"))

Solution 8 - File Io

tidyverse edition with pipe and write_lines() from readr

library(tidyverse)
c('Hello', 'World') %>% write_lines( "output.txt")

Solution 9 - File Io

What about a simple write.table()?

text = c("Hello", "World")
write.table(text, file = "output.txt", col.names = F, row.names = F, quote = F)

The parameters col.names = FALSE and row.names = FALSE make sure to exclude the row and column names in the txt, and the parameter quote = FALSE excludes those quotation marks at the beginning and end of each line in the txt. To read the data back in, you can use text = readLines("output.txt").

Solution 10 - File Io

To round out the possibilities, you can use writeLines() with sink(), if you want:

> sink("tempsink", type="output")
> writeLines("Hello\nWorld")
> sink()
> file.show("tempsink", delete.file=TRUE)
Hello
World

To me, it always seems most intuitive to use print(), but if you do that the output won't be what you want:

...
> print("Hello\nWorld")
...
[1] "Hello\nWorld"

Solution 11 - File Io

Based on the best answer:

file <- file("test.txt")
writeLines(yourObject, file)
close(file)

Note that the yourObject needs to be in a string format; use as.character() to convert if you need.

But this is too much typing for every save attempt. Let's create a snippet in RStudio.

In Global Options >> Code >> Snippet, type this:

snippet wfile
	file <- file(${1:filename})
	writeLines(${2:yourObject}, file)
	close(file)

Then, during coding, type wfile and press Tab.

Solution 12 - File Io

The ugly system option

ptf <- function (txtToPrint,outFile){system(paste(paste(paste("echo '",cat(txtToPrint),sep = "",collapse = NULL),"'>",sep = "",collapse = NULL),outFile))}
#Prints txtToPrint to outFile in cwd. #!/bin/bash echo txtToPrint > outFile
 

Solution 13 - File Io

In newer versions of R, writeLines will preserve returns and spaces in your text, so you don't need to include \n at the end of lines and you can write one big chunk of text to a file. This will work with the example,

txt <- "Hello
World"
fileConn<-file("output.txt")
writeLines(txt, fileConn)
close(fileConn)

But you could also use this setup to simply include text with structure (linebreaks or indents)

txt <- "Hello
   world
 I can 
   indent text!"
fileConn<-file("output.txt")
writeLines(txt, fileConn)
close(fileConn)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionamarillionView Question on Stackoverflow
Solution 1 - File IoMarkView Answer on Stackoverflow
Solution 2 - File IoaL3xaView Answer on Stackoverflow
Solution 3 - File Iops1View Answer on Stackoverflow
Solution 4 - File IopetermeissnerView Answer on Stackoverflow
Solution 5 - File IoGwang-Jin KimView Answer on Stackoverflow
Solution 6 - File IoCharan RajView Answer on Stackoverflow
Solution 7 - File IoGKiView Answer on Stackoverflow
Solution 8 - File IoYuriy BarvinchenkoView Answer on Stackoverflow
Solution 9 - File IoElder DruidView Answer on Stackoverflow
Solution 10 - File Iogung - Reinstate MonicaView Answer on Stackoverflow
Solution 11 - File IoLuis MartinsView Answer on Stackoverflow
Solution 12 - File IokpieView Answer on Stackoverflow
Solution 13 - File IomikeyView Answer on Stackoverflow