How to Concatinate in R with Cat Function

cat function in R will combine character values and print them to the screen or save them in a file directly. The cat function coerces its arguments to character values, then concatenates and displays them. This makes the function ideal for printing messages and warnings from inside of functions

Syntax for cat function in R:

cat(… , file = “”, sep = ” “, fill = FALSE, labels = NULL, append = FALSE)
Arguments:
R objects to be concatenated
file An optional argument that specifies a file to be created, overwritten, or appended
sep Specifies what separates the objects.
append logical. Only used if the argument file is specified. If TRUE, output will be appended to file; otherwise, it will overwrite the contents of file

Simple Cat Function in R:

The cat function will convert the values into character values then combine those values and print them

# simple cat function in R
cat('one',2,'three',4,'five')
output:
one 2 three 4 five

Lets see another simple example for cat function  with only two arguments

# cat function in R with two arguments
cat(1:10,sep="\t")
output:

1    2    3    4    5    6    7    8    9    10

    
cat(1:10,sep="\n")
output:
1
2
3
4
5
6
7
8
9
10

Cat Function in R with File name and Append=False:

Lets look at an example that concatenates the values and stores the value in the Csv file. By default Append = False, so it need not to be mentioned

    
# R cat function with append="FALSE"
cat(1:10,file="num_series.csv",sep="\n",append ="FALSE")

when we execute the above code the output will be stored in the csv file, named num_series.csv

cat function in r with append false

Cat Function in R with File name and Append=TRUE:

Lets look at an example that concatenates the values, Appends and stores the value in the Csv file

    
# R cat function with append="TRUE"
cat(1:10,file="num_series.csv",sep="\n")
cat(11:20,file="num_series.csv",sep="\n",append ="TRUE")

cat function in r with append true

previous small concatenate in R with cat function                                                                                                          next small cat function in r concatinate

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.

    View all posts