Home » How to Use paste & paste0 Functions in R to Concatenate Strings

How to Use paste & paste0 Functions in R to Concatenate Strings

by Tutor Aspire

You can use the paste() and paste0() functions in R to concatenate elements of a vector into a single string.

The paste() function concatenates strings using a space as the default separator.

The paste0() function concatenates strings using no space as the default separator.

These functions use the following basic syntax:

paste(x, sep = " ", collapse = NULL)
paste0(x, collapse = NULL)

where:

  • x: The vector of elements to concatenate
  • sep: The separator to use when concatenating
  • collapse: Value to use when joining elements into single string

The following examples show how to use each function in practice.

Example 1: Use paste0()

The following code shows how to use the paste0() function to concatenate several strings into a single string:

#concatenate several elements into one string
paste0("I", "ride", "my", "bike", 25, "times")

[1] "Iridemybike25times"

Each element is concatenated into one string using no space as the separator.

Example 2: Use paste()

The following code shows how to use the paste() function to concatenate several strings into a single string:

#concatenate several elements into one string
paste("I", "ride", "my", "bike", 25, "times")

[1] "I ride my bike 25 times"

Each element is concatenated into one string using a space as the default separator.

Example 3: Use paste() with sep

The following code shows how to use the paste() function with the sep argument to concatenate several strings into one string, using an underscore as the separator:

#concatenate elements using _ as separator
paste("I", "ride", "my", "bike", 25, "times", sep="_")

[1] "I_ride_my_bike_25_times"

Each element is concatenated into one string using an underscore as the separator.

Example 4: Use paste() with sep and collapse

The following code shows how to use the paste() function with the sep and collapse arguments to concatenate several strings into one string:

#concatenate elements using sep and collapse arguments
paste(c("A", "B", "C"), c(1, 2, 3), sep="_", collapse=" and ")

[1] "A_1 and B_2 and C_3"

The sep argument was used to join together corresponding elements in each vector and the collapse argument was used to join together all of the elements into one string.

Additional Resources

The following tutorials explain how to use other common functions in R:

How to Use the replace() Function in R
How to Use split() Function in R
How to Use the View() Function in R
How to Use all() and any() Functions in R

You may also like