How to write text and output it as a text file using R?

The easiest way to write text and obtain it as an output is done by using writeLines function and cat function, and the output of these functions are connected with the help fileConn and sink.


> fileConn<-file("example1.txt")
> writeLines(c("TutorialsPoint","SIMPLY EASY LEARNING"), fileConn)
> close(fileConn)

We can do the same and view these files in R as follows −

> fileConn <- file("example2.txt")
> writeLines(c(paste("TutorialsPoint", "E-learning"),"2006", "Video Courses", "Tutorials", "Books"), fileConn)
> close(fileConn)

Using sink function

> sink("example3.txt")
> cat("TutorialsPoint", "E-learning")
> cat("
") > cat("2006") > cat("
") > cat("Video Courses") > cat("
") > cat("Tutorials") > cat("
") > cat("Books") > sink()

Using only cat function

> cat("TutorialsPoint E-learning", "2006", "Video Courses", "Tutorials", "Books",file="outfile.txt",sep="
") > cat("Books",file="outfile.txt",append=TRUE)

You can find these files in documents folder of your system.

Updated on: 11-Jul-2020


Kickstart Your Career

Get certified by completing the course

Get Started