Hello, readers! In this article, we will be focusing on 3 Easy Ways to write data to a text file in R, in a simple manner.
So, let us begin! 🙂
With regards to file handing, R programming offers us with various functions to read, write and perform other operations for different formats of data such as csv, excel, text files, and so on.
Today, our center of focus would be text files. We would be exploring different ways to write data to text files in R at an ease!
Writing to a file means framing the data (present into any R data object) to a destination file of a format.
In the course of this article, we will be unveiling the below techniques to write data to a file–
- writeLines() method
- sink() method
- cat() method
So, let us get have a look at them one by one!
Table of Contents
1. Writing to text files in R
R programming provides us with various ways to read data from a file. In a similar fashion, we have
writeLines() function to write data to a text file.
With writeLines() function, we can write data in the form of string, characters or even lists to a text file.
- data: The data to be written to the file.
- connection_object: The object representing the file.
In the below example, we have created a list with the c() function. Further, we have created a connection object for the file. And, have passed the connection object and the data to the function.
conn<-file("abc.txt") writeLines(c("Hello","folks!"), conn) close(conn)
Having completed the task, we close the file operation with close() function.
2. Using sink() function to write data to a file in R
Apart from writeLines() function, R provides us with
sink() function to write the data to a text file. The basic function of the sink() method is to divert the R output to a file connection and even stop them once the target is accomplished.
In this example, we have passed the file name to sink() function, as soon as the compiler encounters sink() function, it diverts all the output values to the file object. Once the transfer is done, we need to use sink() function again to stop the diversion to file.
sink("example.txt") cat("Journaldev welcomes you here!") sink()
3. R cat() function to write data to a file
As seen in the previous articles,
cat() can be considered as an alternative to print() statement. With cat() function, we can impose the data values to a file and append them.
By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question.
For more such posts related to R programming, Stay tuned with us!
Do let us know about your understanding regarding writing data to files with R functions in the comment section.
Till then, Happy Learning!!:)