What is paste() Function in R

The paste() function in R concatenates vectors by converting them into character strings. The function takes three parameters:, sep, and collapse. For example, if you have two vectors x <- c(“a”, “b”, “c”) and y <- c(1, 2, 3), you can use the paste(x, y) function to get “a 1” “b 2” “c 3” or paste(x, y, sep = “-“) to get “a-1” “b-2” “c-3”.

Syntax

The syntax of the paste() function is,

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

Parameters

The x is one or more R objects to be concatenated together.

The sep is a character string to separate the terms.

The default value of collapse is NULL. It is an optional character string to separate the results.

Example 1: How to use paste() function in R

By default, the paste() function in R will accept an unlimited number of scalars and join them together, separating each scalar with space.

paste("Hello", 19, 21, "Mate")

Output

[1] "Hello 19 21 Mate"

Example 2: Passing separator argument to paste() function

If you pass the separator argument to the paste() function, it will separate the elements.

paste("Hello", 19, 21, "Mate", sep = "_")

Output

[1] "Hello_19_21_Mate"

You can see that underscore(_) separator separates the scalars. When combined, the sep= argument controls what is placed between each set of values.

Example 3: Passing the “collapse” argument to the paste() function

The collapse argument can define a value to use when joining those values to create a single string.

When you pass a vector to a paste() function, the separator parameter will not work. That is why we use the collapse parameter, which is beneficial when dealing with the vectors.

paste(c("K", "D", "L"), 1:9, sep = "|", collapse = " & ")

Output

[1] "K|1 & D|2 & L|3 & K|4 & D|5 & L|6 & K|7 & D|8 & L|9"

In this example, the separator (|) will deal with the values which are to be placed in between the set of items, and the collapse argument (&) will make use of specific values to concatenate the items into a single string.

Conclusion

The paste() is a built-in R function used to concatenate vectors by converting them into characters. It takes three parameters and returns a concatenated string.

To concate strings in R, use the paste() function. It is like concatenation using a separation factor, whereas the paste0() is like the append function using a separation factor.

Leave a Comment