在R脚本语言中,如何编写行文本,例如,下面两行

Hello
World

到一个名为output.txt的文件?


当前回答

我将使用cat()命令,如下例所示:

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

然后,您可以使用R with查看结果

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

其他回答

一个简单的writeLines()是什么?

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

or

txt <- c("Hallo", "World")
writeLines(txt, "outfile.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

为了完善可能性,你可以使用writeLines()和sink(),如果你想:

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

对我来说,使用print()似乎总是最直观的,但如果你这样做,输出将不是你想要的:

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

我建议:

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

它比目前公认的答案更简短、更直接。 没有必要做:

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

因为writeLines()的文档说:

如果con是字符串,则函数调用file获取 在函数运行期间打开的文件连接 调用。

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

我将使用cat()命令,如下例所示:

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

然后,您可以使用R with查看结果

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