Write lines of text to a file in R

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

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

回答1:

fileConn


回答2:

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 


回答3:

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 


回答4:

What's about a simple writeLines()?

txt 

or

txt 


回答5:

1.Using file argument in cat.

 cat("Hello World", file="filename") 

2.Use sink function to redirect all output from both print and cat to file.

 sink("filename")                     # Begin writing output to file  print("Hello World")  sink()                               # Resume writing output to console 

NOTE: The print function cannot redirect its output, but the sink function can force all output to a file.

3.Making connection to a file and writing.

con 


回答6:

You could do that in a single statement

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


回答7:

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" 


回答8:

Based on the best answer:

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 

Then, during coding, type wfile and press Tab.



回答9:

The ugly system option

ptf ",sep = "",collapse = NULL),outFile))} #Prints txtToPrint to outFile in cwd. #!/bin/bash echo txtToPrint > outFile 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!