What is the manipulation of strings using paste() in R?

Overview

The paste() function performs manipulation on strings. With the help of paste(), we can append different strings together to form a single string.

The sep in paste() can be used as a separator. The sep inserts special characters, symbols, and digits. We can then join different vectors with the help of paste().

Syntax

paste (......., sep = " ", collapse = NULL)

Parameters

  1. ...... : These are one or more R objects to be concatenated together.
  2. sep: This is a character string to separate the terms.
  3. collapse: This is an optional character string to separate the results.

Example

# Without using seperator
paste("Hello", "I just landed", "and reached home")
# With using seperator
paste("Hello", "I just landed", "and reached home", sep='/')
# Vectors of equal length
paste(c("Hello", "Namaste", "Whats up"), c("Ram", "Shyam", "David"))
# Vectors of unequal length
paste(c("Namaste"), c("Ram", "Shyam", "David"))
paste("Hello", c("Ram", "Bob","Krishna"), c("Goodbye", "Seeya"))
# Using collapse as an argument
vect<-c("HeyRam","Lets catch up soon","Long time")
paste(vect,collapse="!")

Explanation

Line 2: We try to merge different strings and form a single string using the paste() function.

Line 4: We try to use / as a separator between the strings.

Line 6: We create two different vectors of equal length and concatenate them using paste().

Lines 8–9: With vectors of unequal length, the vector is concatenated with each string of another vector. We use paste() .

Lines 11 and 12: The collapse argument here is an optional argument that can be used with vectors.

Free Resources