R cat() Function

The cat() function in R is used to convert its arguments to character strings, concatenate them, separate them by the given separator, and then print them to the console or in a file.

The cat() function differs from print() in that it converts its arguments to character vectors, concatenates them, and does not include additional formatting like quotes around strings.

Syntax

cat(… , file = "", sep = " ", fill = FALSE, labels = NULL, append = FALSE)

Parameters

  1. …: It is an R object.
  2. file: It is a connection or a character string naming the file to print. If ” “ (the default), the cat() function prints to the standard output connection.
  3. sep: It is a character vector of strings to append after each element.
  4. fill: It is a logical or (positive) numeric, controlling how the output is broken into successive lines.
  5. labels: They are a character vector of labels for the lines printed. Ignored if the fill is FALSE.
  6. append: It is a logical value. They are only used if the argument file is the file’s name (not a connection or “|cmd”).

Return Value

It returns None (invisible NULL).

The output of cat() cannot be assigned to a variable. It’s used for side effects (i.e., printing).

Example 1: Concatenating objects

Visualization of cat() Function in R

cat("Elon", "Musk", "Buys", 1.5, "Billion", "of Bitcoin")

Output

Elon Musk Buys 1.5 Billion of Bitcoin

Example 2: Using with custom separator

Figure of using cat() function with custom separator

You can see in the diagram that we are concatenating and printing the numbers from 18 to 21, each on a new line. The sep = “\n” argument ensures that each number is printed on a new line.

cat(18:21, sep = "\n")

Output

18
19
20
21

Example 3: Returning NULL

data <- cat(18:21, "\n")

is.null(data)

Output

18 19 20 21
[1] TRUE

Example 4: Output results to file

cat("hello", "Krunal", "Not Good",
    file = "myfile.csv", sep = "\n", append = "FALSE"
)

It will create a CSV file with string values. Each value will be in a new line since we have passed sep = “\n”.

Output

cat() Function in R to Concatenate Objects

Example 5: Usage with file and Append=TRUE

If you pass append = TRUE, it will append the text to the existing content of the file and not override it.

cat(18:21, file="data.csv", sep = "\n", append ="TRUE")

Output

18
19
20
21
18
19
20
21

That’s it.

Leave a Comment