如何使用 R 编写文本并将其输出为文本文件?
通过使用 writeLines 函数和 cat 函数可以最方便地编写文本并将其作为输出获得,这些函数的输出将通过 fileConn 和 sink 连接。
示例
> fileConn<-file("example1.txt") > writeLines(c("TutorialsPoint","SIMPLY EASY LEARNING"), fileConn) > close(fileConn)
我们可以执行相同的操作,并在 R 中查看这些文件,如下所示 −
> fileConn <- file("example2.txt") > writeLines(c(paste("TutorialsPoint", "E-learning"),"2006", "Video Courses", "Tutorials", "Books"), fileConn) > close(fileConn) > file.show("example.txt")
使用 sink 函数
> sink("example3.txt") > cat("TutorialsPoint", "E-learning") > cat("
") > cat("2006") > cat("
") > cat("Video Courses") > cat("
") > cat("Tutorials") > cat("
") > cat("Books") > sink()
仅使用 cat 函数
> cat("TutorialsPoint E-learning", "2006", "Video Courses", "Tutorials", "Books",file="outfile.txt",sep="
") > cat("Books",file="outfile.txt",append=TRUE)
可以在系统文档文件夹中找到这些文件。
广告