ChatGPT解决这个技术问题 Extra ChatGPT

Write lines of text to a file in 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"?


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

Mark - what If I have several threads all of which I would like to add lines to the same file? (The issue being is that you can't have more then one connection to a file, If I am not mistaken) Thanks.
@Tal, that is an excellent question, you should post it as a new, separate question so it'll get some attention. There are much more knowledgeable R programmers around here than me!
Note that this requires the file "output.txt" to already exist. If it doesn't, it must be created first, e.g. using 'file.create("output.txt")'.
@jhin I am not sure if that is true. Using RStudio 0.98 and R version 3.1.0 the file is created automatically if it doesn't exist
The option of writeLines() is roughly ten times faster then the combination of sink() and cat()
G
Gregor Thomas

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

sink() doesn't work on Databricks be careful. You can use put all these inside a function and call this function like capture.output(funciton call, filename)
Thanks for this @aL3xa. But keep in mind that this code effectively writes everything from the console, including the code exectured.
p
ps1

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

It constantly opens & closes a file. This approach might be inefficient.
p
petermeissner

What's about a simple writeLines()?

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

or

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

nice to show that the input doesn't have to be a vector of lines
@tim Actually "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)
This works for me only as writeLines(txt, con="outfile.txt").
nope, should work without naming arguments as long as you give a valid file name as second argument.
@petermeissner > coefficients<-summary(model) > writeLines(coefficients, "coefficients") Error in writeLines(coefficients, "coefficients") : invalid 'text' argument
C
Charan Raj

You could do that in a single statement

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

G
Gwang-Jin Kim

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.

It's good to add that writeLines can print only character vectors.
G
GKi

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

Y
Yuriy Barvinchenko

tidyverse edition with pipe and write_lines() from readr

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

E
Elder Druid

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").


g
gung - Reinstate Monica

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"

P
Palec

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.


The 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...
it worked on my setup @Palec You can change file to youFile if you have some problem with reserved words
k
kpie

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

m
mikey

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)