Tutorial

How to use sink() function in R

Published on August 3, 2022
Default avatar

By Prajwal CN

How to use sink() function in R

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

You can use sink() function in R to drive the data to the external connections.

Hello folks, today we will be looking into the applications of the sink() function in R. We are going to try to make connections in multiple formats such as text and csv file types.

Using the sink() function, you can either print the data or you can export the data or the R output to text or CSV file types.

Let’s see how it works!


The syntax of sink() function in R

Sink(): The sink function is used to drive the output obtained in R to the external connection.

sink(file = NULL, type = c("output", "message"),split = FALSE)

Where:

  • File = The editable connection or the file type.
  • Append = The logical function used to append the data to file to avoid overwrite.
  • Split = Output will be diverted to a new connection or link.

1. Setting up the working directory

With the help of sink() function, you can easily print the output to the text file as a connection. We can start this process by setting up the working directory.

To check the current working directory:

#returns the current working directory
getwd()
"C:/Users/Dell/Desktop/rfiles"

Fine. We got the working directory now. And you can also change the working directory using,

#sets the new working directory 
setwd("The directory path here")

Paste the path in the setwd() function to set the new working directory. After that dont forget to confirm the changes using the ‘getwd()’ command as shown above.


2. Printing the data into the text file

I hope you are ready with your working path now. Now we are going to create a file connection and print some data into it.

Let’s see how it works.

#sinks the data into connection as text file
sink("my_first_sink.txt")

#prints numbers from 1 to 20
for (i in 1:20)
print(i)
sink()

Sink In R

Now you can see how neatly our R data is printed into the text file. Awesome right?


3. Exporting the data into text file

In the previous section, we have printed the data or the output to the text file. In this section, we are going to export the entire data set which is available in R by default.

Let’s see how it works.

#exports the data as text file
sink('export_dataframe.txt')
airquality
sink()

Sink Function In R

You can see that the data of air quality data set is driven to the text file as a external connection.

This is how you can easily drive the data in R to connections. You can also export as a csv file as shown below.


4. Exporting the data frame into CSV file

In this section, we are going to drive or export the data into a CSV file using the sink() function in R.

Let’s see how it works.

#export the data as csv file
sink('export_dataframe_1.csv')
iris
sink()

Sink To Csv

Well, this a CSV file that includes the exported data from the R console. sink() function in R offers the easiest way to drive the data to external connections such as a file.


Exporting the summary of the data to connection

So far, So good. Now, lets try to apply what we have learnt or understood by the above sections all together.

The problem statement is simple.

=> Read a data set of your choice and get a summary of the data using the function summary(). Upon doing that, drive the result into the text file as connection.

Let’s rock!!!


1. Let’s read the data

#reads the data
df<-datasets::airquality
df
View(df)

Sink 1

The first step in the problem statement is here. You can see the air quality dataset in the above image.


2. The summary() of the data

The summary of the data using the function summary() can be seen below.

#returns the key insights of data
summary(airquality)
  Ozone           Solar.R           Wind             Temp           Month      
 Min.   :  1.00   Min.   :  7.0   Min.   : 1.700   Min.   :56.00   Min.   :5.000  
 1st Qu.: 18.00   1st Qu.:115.8   1st Qu.: 7.400   1st Qu.:72.00   1st Qu.:6.000  
 Median : 31.50   Median :205.0   Median : 9.700   Median :79.00   Median :7.000  
 Mean   : 42.13   Mean   :185.9   Mean   : 9.958   Mean   :77.88   Mean   :6.993  
 3rd Qu.: 63.25   3rd Qu.:258.8   3rd Qu.:11.500   3rd Qu.:85.00   3rd Qu.:8.000  
 Max.   :168.00   Max.   :334.0   Max.   :20.700   Max.   :97.00   Max.   :9.000  
 NA's   :37       NA's   :7                                                       
      Day      
 Min.   : 1.0  
 1st Qu.: 8.0  
 Median :16.0  
 Mean   :15.8  
 3rd Qu.:23.0  
 Max.   :31.0  

This is the summary of the data which shows the minimum and maximum values, quartiles, median, mean and more insights.

3. Driving the output to the connection

Now, all you need to do is to export it into text file and make it as a external connection.

#drive the output data to txt file
sink('problem-solution.txt')
summary(airquality)
sink()

Sink 3


4. End the connection

You have got all the steps right and successfully driven the data into text file as a external connection.

Now its time to end the connection.

#terminates the connection 
unlink('problem-solution.txt')

The above command will delete the file connection.

To sum up all the steps,

  • Read the data in the R console.
  • Apply the summary() function to the data.
  • Get key insights on data.
  • Drive the findings to the text file using the sink() function in R.

Wrapping Up

The sink() function in R drives the R output to the external connection. You can export the data in multiple forms such as text and CSV files. You can either print the data into the connection or directly export the entire data to it.

After the data transfer, you can unlink the connection to terminate the file.

The sink() function in R is useful in many ways as it offers temporary connections to work with data.

More read: R documentation

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Prajwal CN

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel