Home » The Difference Between cat() and paste() in R

The Difference Between cat() and paste() in R

by Erma Khan

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 #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.

If we store the results of the concatenation in a variable, we can then reference that variable to view the concatenated string:

#concatenate several strings together
results #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.

Additional Resources

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

How to Use paste & paste0 Functions in R
How to Use the dim() Function in R
How to Use the map() Function in R

Related Posts