paste0() Function in R

R paste0() function concatenates strings without any separator between them. It is a shorthand version of paste(…, sep = “”).

Visual representation of paste0() function

paste0("Data", "Matics")

# Output: [1] "DataMatics" paste0(letters[18:22])

# Output: [1] "r" "s" "t" "u" "v"

It is helpful for generating variable names, file paths, labels, and identifiers in a vectorized, compact way.

Syntax

paste0(…, collapse = NULL)

Parameters

Argument Description
It is one or more R objects to be concatenated element-wise.
collapse It is an optional character string to separate the results.

Passing the ‘collapse’ argument

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 key difference between paste0() and paste() is that paste0() does not have a “sep” argument and thus concatenates strings without any separator, whereas the paste() function uses space as a default separator.

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

st

# Output: [1] "Eleven  Mike  Dustin"

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

st1

# Output: [1] "ElevenMikeDustin"

Vector recycling

Vector recycling in R

If you are trying to merge two vectors in which both vectors have different lengths, the paste0() method handles vectors of unequal lengths by recycling the shorter vector.

paste0("ID", 1:5)

# Output: [1] "ID1" "ID2" "ID3" "ID4" "ID5"

You can see that ID is the shorter vector, and it is recycled 5 times since the other vector has 5 elements.

Type coercion

Type coercion in paste0() function

If your input vector contains non-character types, then non-character inputs are coerced to character strings. That automatic conversion is called type coercion.

paste0("Krunal_", 21, "_Stranger_", TRUE)

# Output: [1] "Krunal_21_Stranger_TRUE"

In the above code, you can see that Numeric (21) and logical (TRUE) inputs are converted to their character representations.

Handling NA values

Handling NA values

If your input vector contains an NA value, the output will be NA too unless it is handled explicitly.

paste0("Kaynes", c("BSE", NA, "NSE"))

# Output: [1] "KaynesBSE" "KaynesNA" "KaynesNSE"

Empty input

If the input is empty, the output of paste0() will be character(0).

paste0()

# Output: character(0)

Empty string

What if the string is empty? The output will be an empty string, too! Remember, empty input and an empty string are two different objects.

paste0("")

# Output: [1] ""

NULL

If the input contains NULL, it will be ignored, and only non-NULL values will be concatenated.

paste0(NULL, "Kaynes")

# Output: [1] "Kaynes"

That’s it!

Leave a Comment