How to Save R Output to Text File (With Examples)


There are two common ways to save R output to a text file:

Method 1: Use the sink() Function

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

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

#close the external connection
sink() 

Method 2: Use the cat() Function

#write string to file
cat("here is some text", file = "my_data.txt")

The following examples show how to use each method in practice.

Example 1: Save R Output to Text File Using sink()

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 string 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 use the cat() function to export something more complex like 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 2: Save R Output to Text File Using cat()

We can use the following cat() function to save a string to a text file:

#save string to text file
cat("here is some text", file = "my_data.txt")

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

The text file contains the string that we specified.

Notice that the cat() function doesn’t include any line numbers from the R console in the text file, unlike the sink() function.

Feel free to use whichever function suits your needs.

Additional Resources

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

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

Featured Posts

Leave a Reply

Your email address will not be published. Required fields are marked *