在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
其他回答
fileConn<-file("output.txt")
writeLines(c("Hello","World"), fileConn)
close(fileConn)
简单的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")。
丑陋的系统选项
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"
实际上你可以用sink()来实现:
sink("outfile.txt")
cat("hello")
cat("\n")
cat("world")
sink()
因此做:
file.show("outfile.txt")
# hello
# world