paste0 in R: How to Use paste0() Function in R

The paste() and paste0() functions combine several inputs into a character string. We have already seen the paste() function, one of the most used functions in R. 

paste0 in R

The paste0() is a built-in R function used to concatenate all elements without a separator. The paste0() function accepts one or more R objects as arguments and optional collapse argument.

The paste0() is faster than paste() if our objective is to concatenate strings without spaces because we don’t have to specify the argument sep.

Syntax

paste0(…, collapse = NULL)

Parameters

…: It is one or more R objects to be converted to character vectors.

collapse: It is an optional character string to separate the results.

Example

paste0("Data", "Matics")
paste0("Data", " Dog")
paste0(letters[18:22])

Output

[1] "DataMatics"
[1] "Data Dog"
[1] "r" "s" "t" "u" "v"

By default, paste0() uses sep = “” (For example, no separator at all). This can be convenient in case you don’t want to use a separator anyway.

Passing collapse argument to the paste0()

The paste0() function accepts the collapse argument. So let’s pass that argument and see the result.

paste0("Data", collapse = " ")
paste0("Dog", collapse = "/")
paste0(letters[18:22], collapse = "*")
paste0("K", 1:7)

Output

[1] "Data"
[1] "Dog"
[1] "r*s*t*u*v"
[1] "K1" "K2" "K3" "K4" "K5" "K6" "K7"

Difference between paste and paste0

The paste0() function is a simplified form of the paste function, which uses no separator.

The difference between paste() and paste0() is that the argument sep by default is “” (paste) and “” (paste0).

st <- paste("Eleven", "Mike", "Dustin", sep = "")
st

# Default value of sep with paste function
st1 <- paste0("Eleven", "Mike", "Dustin")
st1

Output

[1] "ElevenMikeDustin"
[1] "ElevenMikeDustin"

That is it for this tutorial.

Leave a Comment