paste0 in R: How to Use paste0() Function

The paste() and paste0() functions combine several inputs into a character string. To know more about the paste() function, check out the paste() in R article.

paste0 in R

The paste0() in R is a built-in function used to concatenate the strings without adding any separator. It is similar to the paste() function with the difference that the paste0() function does not add a space or any other separator between the strings, whereas the paste() function does add a space by default.

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.

The paste0() function accepts one or more R objects as arguments and optional collapse arguments.

How to use paste0() function in R

To use the paste0() function, you must pass the strings you want to concatenate as arguments to the function.

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 if you don’t want to use a separator.

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