R Tutorials by : Er Karan Arora : Founder & CEO - ITRONIX SOLUTIONS

1: Cat function in R

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

  • one or more R objects, to be concatenated together.
  • sep a character string to separate the terms.
  • collapse an optional character string to separate the results.

Simple Cat Function in R:

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

In [1]:
cat('one',2,'three',4,'five')
one 2 three 4 five

cat function in R with two arguments

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

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

In [9]:
cat(1:10,file="num_series.csv",sep="\n",append ="FALSE")
In [10]:
cat(1:10,file="num_series.csv",sep=",",append ="FALSE")

R cat function with append="TRUE"

In [11]:
cat(1:10,file="num_series.csv",sep="\n")
cat(11:20,file="num_series.csv",sep="\n",append ="TRUE")

2: Paste function in R

Paste function in R is used to concatenate Vectors by converting them into character. paste0 function in R simply concatenates the vector with space separator. lets see an example of paste() Function in R and Paste0() Function in R

Syntax for Paste Function in R

  • paste (…, sep = ” “, collapse = NULL)

Arguments

  • one or more R objects, to be concatenated together.
  • sep a character string to separate the terms.
  • collapse an optional character string to separate the results.

Simple Paste Function in R:

In its simplest usage, paste function in R will accept an unlimited number of scalars, and join them together, separating each scalar with a space by default

In [12]:
paste('one',2,'three',4,'five')
'one 2 three 4 five'

paste function in R with sep argument

In [13]:
paste('X',1:5,sep='')
  1. 'X1'
  2. 'X2'
  3. 'X3'
  4. 'X4'
  5. 'X5'

paste function in R with collapse argument

In [14]:
paste(c('one','two','three','four'),collapse=' and ')
'one and two and three and four'

paste function in R with separator and collapse Argument

In [16]:
paste(c('X','Y'),1:5,sep='_',collapse=' and ')
'X_1 and Y_2 and X_3 and Y_4 and X_5'

3: Paste0() Function in R

Paste0() is a simple paste() function with default separator “ ”. paste0() Function will take only two arguments as shown below

In [18]:
paste0('X',1:5)
  1. 'X1'
  2. 'X2'
  3. 'X3'
  4. 'X4'
  5. 'X5'
In [19]:
paste0('X',1:5,collapse=",")
'X1,X2,X3,X4,X5'
In [ ]: