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.
We use the paste()
function to combine both a text and a variable in R.
name <- 'Theo'paste('my name is', name)
We see that the
paste()
function concatenates elements and also adds a space between the concatenated elements.
To concatenate two variables in R, we use the paste()
function and ,
.
name <- 'Theo'age <- 20paste(name, age)
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.
a = 10b = 20paste(a, b)
a <- as.character(10)b <- as.character(20)paste(a, b)
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:
name <- 'Theo'age <- 20age + name