Write lines of text to a file in R

2019-01-03 11:29发布

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 r
9条回答
倾城 Initia
2楼-- · 2019-01-03 11:56

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.

查看更多
3楼-- · 2019-01-03 12:00

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
查看更多
趁早两清
4楼-- · 2019-01-03 12:01

What's about a simple writeLines()?

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

or

txt <- c("Hallo", "World")
writeLines(txt, "outfile.txt")
查看更多
仙女界的扛把子
5楼-- · 2019-01-03 12:01

You could do that in a single statement

cat("hello","world",file="output.txt",sep="\n",append=TRUE)
查看更多
放我归山
6楼-- · 2019-01-03 12:03

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
查看更多
Root(大扎)
7楼-- · 2019-01-03 12:04

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
查看更多
登录 后发表回答