What is the difference between cat() and paste() in R?

The cat() and paste() functions in R are used to combine two or more strings into one. The difference between them is that the cat() function will simply concatenate the strings together, while the paste() function allows for further customization such as adding a separator between the strings and controlling the order of the strings being combined.


The cat() and paste() functions in R can both be used to concatenate strings together, but they’re slightly different in the following way:

  • The cat() function will output the concatenated string to the console, but it won’t store the results in a variable.
  • The paste() function will output the concatenated string to the console and it will store the results in a character variable.

In general, the cat() function is used more often for debugging.

By contrast, the paste() function is used when you’d like to store the results of the concatenation in a character variable and reference that variable later on in your code.

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

Example: How to Use the cat() Function

The following code shows how to use the cat() function to concatenate together several strings:

#concatenate several strings together
cat("hey", "there", "everyone")

hey there everyone

Notice that the cat() function concatenates the three strings into a single string and outputs the results to the console.

However, if we attempt to store the results of the concatenation in a variable and then view that variable, we’ll receive a NULL value as a result:

#concatenate several strings together
results <- cat("hey", "there", "everyone")

hey there everyone

#attempt to view concatenated string
results

NULL

This is because the cat() function does not store results.

It merely outputs the results to the console.

Example: How to Use the paste() Function

The following code shows how to use the paste() function to concatenate together several strings:

#concatenate several strings together
paste("hey", "there", "everyone")

[1] "hey there everyone"

Notice that the paste() function concatenates the three strings into a single string and outputs the results to the console.

#concatenate several strings together
results <- paste("hey", "there", "everyone")

#view concatenated string
results

[1] "hey there everyone"

We’re able to view the concatenated string because the paste() function stores the results in a character variable.

We can also use functions like nchar() to view the length of the concatenated string:

#display number of characters in concatenated string
nchar(results)

[1] 18

We can see that the concatenated string contains 18 characters (including spaces).

We would not be able to use the nchar() function with cat() since cat() doesn’t store the results in a variable.

The following tutorials explain how to use other common functions in R:

x