How to Use the sink() Function in R (With Examples)


You can use the sink() function to drive R output to an external connection.

This function is useful because it lets you easily export character strings or data frames to a CSV file or text file.

This function uses the following basic syntax:

#define file name
sink("my_data.txt")

#write this text to file
"here is some text"

#close the external connection
sink() 

The following examples show three different ways to use this function in practice.

Example 1: Use sink() to Export String to Text File

We can use the following sink() function to export a character string to a text file:

#define file name
sink("my_data.txt")

#write this text to file
"here is some text"

#close the external connection
sink()

We can then navigate to the current working directory and open the text file:

The file contains the string that we specified.

We can also export several character strings to a text file:

#define file name
sink("my_data.txt")

#write several strings to file
"first text"
"second text"
"third text"

#close the external connection
sink()

We can then navigate to the current working directory and open the text file:

The file contains the three strings that we specified.

Example 2: Use sink() to Export Data Frame to Text File

We can use the following sink() function to export a data frame to a text file:

#define file name
sink("my_data.txt")

#define data frame to write to file
df <- data.frame(player=c('A', 'B', 'C', 'D','E'),
                 points=c(12, 29, 24, 30, 19),
                 assists=c(5, 5, 7, 4, 10))

print(df)

#close the external connection
sink()

We can then navigate to the current working directory and open the text file:

The file contains the data frame that we created.

Example 3: Use sink() to Export Data Frame to CSV File

We can use the following sink() function to export a data frame to a CSV file:

#define file name
sink("my_data.csv")

#define data frame to write to file
df <- data.frame(player=c('A', 'B', 'C', 'D','E'),
                 points=c(12, 29, 24, 30, 19),
                 assists=c(5, 5, 7, 4, 10))

print(df)

#close the external connection
sink()

We can then navigate to the current working directory and open the CSV file:

The CSV file contains the data frame that we created.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Export a Data Frame to an Excel File in R
How to Export a Data Frame to a CSV File in R

Leave a Reply

Your email address will not be published.