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
- …: It is an R object.
- 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.
- sep: It is a character vector of strings to append after each element.
- fill: It is a logical or (positive) numeric, controlling how the output is broken into successive lines.
- labels: They are a character vector of labels for the lines printed. Ignored if the fill is FALSE.
- 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
cat("Elon", "Musk", "Buys", 1.5, "Billion", "of Bitcoin")
Output
Elon Musk Buys 1.5 Billion of Bitcoin
Example 2: Using 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
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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.