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

Hello
World

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


当前回答

简单的write.table()怎么样?

text = c("Hello", "World")
write.table(text, file = "output.txt", col.names = F, row.names = F, quote = F)

参数col.names = FALSE和row.names = FALSE确保排除txt中的行名和列名,参数quote = FALSE排除txt中每行开头和结尾的引号。 要将数据读入,可以使用text = readLines("output.txt")。

其他回答

实际上你可以用sink()来实现:

sink("outfile.txt")
cat("hello")
cat("\n")
cat("world")
sink()

因此做:

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

丑陋的系统选项

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"

在R的新版本中,writeLines将保留文本中的返回值和空格,因此您不需要在行末包含\n,并且可以将一大块文本写入文件。这个例子也适用,

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

但是您也可以使用此设置简单地包含具有结构的文本(换行或缩进)

txt <- "Hello
   world
 I can 
   indent text!"
fileConn<-file("output.txt")
writeLines(txt, fileConn)
close(fileConn)

我建议:

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.