Home » How to Use the cat() Function in R to Concatenate Objects

How to Use the cat() Function in R to Concatenate Objects

by Erma Khan

The cat() function in R can be used to concatenate together several objects in R.

This function uses the following basic syntax:

cat(..., file = "", sep = " ", append = FALSE))

where:

  • : Objects to concatenate
  • file: File name to send output to
  • sep: Separator to use between objects
  • append: Whether to append output to existing file or create new file

The following examples show how to use this function in different ways.

Example 1: Use cat() to Concatenate Objects

We can use the cat() function to concatenate three strings in R:

#concatenate three strings
cat("hey", "there", "everyone")

hey there everyone

The three strings are concatenated together, with each string separated by a space.

Example 2: Use cat() to Concatenate Objects with Custom Separator

We can use the cat() function to concatenate three strings in R, using a dash as the separator:

#concatenate three strings, using dash as separator
cat("hey", "there", "everyone", sep="-")

hey-there-everyone

Or we could use “n” as the separator, which species that each string should be separated by a new line:

#concatenate three strings, using new line as separator
cat("hey", "there", "everyone", sep="n")

hey
there
everyone

Example 3: Use cat() to Concatenate Objects and Output Results to File

We can use the cat() function to concatenate three strings in R and output the results to a text file:

#concatenate three strings and output results to txt file
cat("hey", "there", "everyone", sep="n", file="my_data.txt")

I can then navigate to my current working directory and view the contents of this text file:

We could also output the results to a CSV file:

#concatenate three strings and output results to CSV file
cat("hey", "there", "everyone", sep="n", file="my_data.csv")

I can then navigate to my current working directory and view the contents of this text file:

Example 4: Use cat() to Concatenate Objects and Append Results to File

We can use the cat() function to concatenate three strings in R and append the results to an existing CSV file:

#concatenate three strings and output results to CSV file
cat("hey", "there", "everyone", sep="n", file="my_data.csv")

#append results of this concatenation to first file
cat("how", "are", "you", sep="n", file="my_data.csv", append=TRUE)

I can then navigate to my current working directory and view the contents of this CSV file:

Notice that the results of the second cat() function have been appended to the file created by the first cat() function.

Additional Resources

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

How to Use sprintf Function in R to Print Formatted Strings
How to Use strsplit() Function in R to Split Elements of String
How to Use substring() Function in R to Extract Substring

Related Posts