在R脚本语言中,如何编写行文本,例如,下面两行
Hello
World
到一个名为output.txt的文件?
在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
其他回答
在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)
实际上你可以用sink()来实现:
sink("outfile.txt")
cat("hello")
cat("\n")
cat("world")
sink()
因此做:
file.show("outfile.txt")
# hello
# world
fileConn<-file("output.txt")
writeLines(c("Hello","World"), fileConn)
close(fileConn)
我将使用cat()命令,如下例所示:
> cat("Hello",file="outfile.txt",sep="\n")
> cat("World",file="outfile.txt",append=TRUE)
然后,您可以使用R with查看结果
> file.show("outfile.txt")
hello
world
你可以用一个语句来做
cat("hello","world",file="output.txt",sep="\n",append=TRUE)