cat() function in R

cat() function in R is used to print and concatenate data to the console. The data can be strings, integers, vectors, data frames, or any R object. The cat() function can be used to print multiple strings of data or vectors to the console. The function will print each data or vector on a new line.

The function can also be used to merge two or more data sets together. For example, you might want to join two data frames together so they contain the same data in the same order. In this guide, we’ll show you how to use the cat() function in R.


cat(objects, file, sep, append)


  • objects = one or more R objects like string, vector, list, matrix, or data frame.
  • file = any name you want to give to an output file followed by the file extension. For example, payments.csv
  • sep = stands for separator and will be used to separate each object. Commonly used separators are dash(-), forward slash(/), or underscore(_)
  • append = takes TRUE or FALSE. If TRUE, then appends the object to the mentioned file. By default, it is FALSE.

Example 1: Print a Single String of Text to the Console

cat('R Programming')


R Programming

Example 2: Print Multiple String of Text to the Console

cat('R', 'Programming')


R Programming

Example 3: Print the Values of Variables

#creating a variable
x = 25
#printing the data with variable
cat('My age is ', x)


My age is 25

Example 4: Print a Vector of Strings

#creating a vector
x <- c('R', 'Programming')
#printing the vector


R Programming

Example 5: Using cat() to Merge R Objects

cat('I', 'Love', 'R', 'Programming')


I Love R Programming

Example 6: Using cat() to Merge R Objects with a Separator

cat('I', 'Love', 'R', 'Programming', sep = '-')



Example 7: Using cat() to Merge and Print to a File

In this example, we are using cat() with the file argument to return the merged value in a new file. Make sure to mention the filename with an extension like txt, csv, doc, or xlsx. Also, keep in mind that the output file can be located in the current working directory.

cat('I', 'Love', 'R', 'Programming', sep = '-', file = 'sample.txt')



cat() with the file parameter
Using cat() with the file parameter.

The output is a sample.txt file with merged data.

Example 8: Using cat() Append the Objects to an Existing File

In this example, we use cat() with the Append argument to append the data to an existing file. Remember that the existing file should be in the current working directory.

cat(' How', 'to', 'Concatenate', 'in','R', sep = '-', file = 'sample.txt', append = TRUE)


cat() with the append parameter
Using cat() with the append parameter

You will notice that the sample.txt has been appended with the new data.

Leave a Comment