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"?
fileConn<-file("output.txt")
writeLines(c("Hello","World"), fileConn)
close(fileConn)
writeLines()
is roughly ten times faster then the combination of sink()
and cat()
Commented
Oct 1, 2015 at 9:36
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
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
What's about a simple writeLines()
?
txt <- "Hallo\nWorld"
writeLines(txt, "outfile.txt")
or
txt <- c("Hallo", "World")
writeLines(txt, "outfile.txt")
"Hallo\nWorld"
is a length one vector of the character type. Just try txt <- "Hallo\nWorld"; is.character(txt) && length(txt) == 1 && is.vector(txt)
writeLines(txt, con="outfile.txt")
.
> coefficients<-summary(model) > writeLines(coefficients, "coefficients") Error in writeLines(coefficients, "coefficients") : invalid 'text' argument
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 callsfile
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.
You could do that in a single statement
cat("hello","world",file="output.txt",sep="\n",append=TRUE)
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"))
Append to an existing file is easier with cat
. But this option will permanently open and close the file for each transaction. So for many appending writings a connection might be preferable. The a
in the command file
stands for Open for appending in text mode. Another option will be w
for Open for writing in text mode to create a new file for writing.
cat("Hello\n", file="output.txt")
cat("World", file="output.txt", append=TRUE)
cat("Hello\n", file="output.txt")
CON <- file("output.txt", "a")
cat("World", file=CON)
close(CON)
writeLines("Hello", "output.txt")
CON <- file("output.txt", "a")
writeLines("World", CON)
close(CON)
On the other hand writeLines
is faster than cat
.
bench::mark(check=FALSE,
writeLines(c("Hello", "World")),
cat("Hello", "World", sep="\n"),
writeLines(c("Hello", "World"), sep=" "),
cat(c("Hello", "World")),
cat("Hello", "World") )
# expression min median `itr/sec` mem_a…¹
# <bch:expr> <bch:tm> <bch:tm> <dbl> <bch:b>
#1 writeLines(c("Hello", "World")) 2.27µs 4.77µs 163878. 0B
#2 cat("Hello", "World", sep = "\n") 3.83µs 8.51µs 118708. 0B
#3 writeLines(c("Hello", "World"), sep = " ") 1.99µs 4.25µs 235944. 0B
#4 cat(c("Hello", "World")) 4.1µs 6.84µs 141797. 0B
#5 cat("Hello", "World") 3.46µs 7.06µs 129865. 0B
tidyverse edition with pipe and write_lines()
from readr
library(tidyverse)
c('Hello', 'World') %>% write_lines( "output.txt")
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")
.
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
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"
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.
file <- file(...)
line looks suspicious to me. Isn't it both invoking file
as a function and assigning file
a new meaning? Does file()
work even after this piece of code runs? Don't have access to an R installation to test myself right now...
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)