paste and paste0
   get_help() docs


Description

The paste() and paste0() functions come with R and are part of the Base R {base} package.

We use these functions to combine multiple strings (or other values that will be coerced into characters) into one. The paste() function combines all provided strings separated by a space or a provided other “separator.” The paste0() function combines all provided strings without any separator.

For a slightly more convenient way to combine strings, the glue() function from the {glue} package, makes it easier to combine strings with previously-defined variables. Learn more by running get_help("glue").

Conceptual Usage

# Combine with spaces
paste(these, strings, will, be, combined, into, a, single, long, string, separated, by, a, space)

# Combine with `!` separating the strings using sep
paste(use, the, sep, argument, to, change, how, these, are, separated, 
      sep = "how those strings should be separated?"

# When combining strings in an array, use `collapse` instead of `sep`
paste( c(these, strings, are, inside, an array), 
       collapse = "how those strings should be separated")

# Combine with nothing separating the strings
paste0(these, strings, will, be, combined, into, a, single, long, string, without, any, separation)

# Setting sep = "" is equivalent to paste0()
paste(equivalent, to, paste0, sep = "")

Examples


# Combine the following substrings into the resulting sentence
# A space is placed between each string
favorite_animal <- "tardigrades"
paste("I love", favorite_animal, "the most.")
## [1] "I love tardigrades the most."


# Combine the following substrings into the resulting "sentence," separated by a semi-colon `;`
favorite_animal <- "tardigrades"
paste("I love", favorite_animal, "the most.", sep = ";")
## [1] "I love;tardigrades;the most."


# Combine the following substrings into the resulting "sentence," not separated at all with paste0()
# Original spaces remain, but nothing was added between "I love"/"tardigrades" and "tardigrades"/"the most."
favorite_animal <- "tardigrades"
paste0("I love", favorite_animal, "the most.")
## [1] "I lovetardigradesthe most."


# To combine all strings _in an array_ into a single string, use the argument `collapse` instead of `sep` to combine with
favorite_animals <- c("tardigrades", "rotifers", "axolotls")
paste(favorite_animals, collapse="-")
## [1] "tardigrades-rotifers-axolotls"