What is the paste() function in R?

Overview

The concatenation of elements in R is simply a way of joining two or more elements. To join multiple elements in R, we use the paste() function.

The paste() function adds a space between the concatenated elements. The subsequent sections illustrate this.

Text and variable concatenation

We use the paste() function to combine both a text and a variable in R.

Code

name <- 'Theo'
paste('my name is', name)

We see that the paste() function concatenates elements and also adds a space between the concatenated elements.

The concatenation of two variables

To concatenate two variables in R, we use the paste() function and ,.

Code

name <- 'Theo'
age <- 20
paste(name, age)

The concatenation of numbers

We use the paste() function to join numbers in R too.

It is worth noting that the numbers can be first converted to a string using the as.character() function. Then the paste() function concatenates them.

Code

a = 10
b = 20
paste(a, b)
a <- as.character(10)
b <- as.character(20)
paste(a, b)

Explanation

We convert the numeric objects to a string character using the as.character() method in the code above.

Note: Trying to join a number and a text(string) variable in R will return an error message.

Take a look at the code below:

Code

name <- 'Theo'
age <- 20
age + name

Free Resources