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