Was it helpful?

Question

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

R ProgrammingServer Side ProgrammingProgramming

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.

Example

> 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)
> file.show("example.txt")

Using sink function

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

Using only cat function

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

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

raja
Published on 06-Jul-2020 18:32:40
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top