To save R output to text file, you can use sink() function or cat() function in R.

The following methods show how you can do it with syntax.

Method 1: Use sink() Function

# Rredirecting output to a file
sink("file.txt")

# Save output in file
print("output")

# Close the file
sink()

Method 2: Use cat() Function

cat("output",file = "file.txt")

The following examples show how to save R output in text file using two different methods.

Use sink() Function

Let’s see how we can use sink() function in R:

# Define file name 
sink("sample.txt")

# Send output to text file
print("This is R language output")

# Close connection with file
sink()

Here in the above code we save text data in sample.txt file using sink() function.

Using cat() Function

Let’s see how we can use cat() function in R:

# Save string to text file
cat("We are learning R language", file = "sample1.txt")

Here in the above code we save text data into sample1.txt file.