There are multiple ways how to concatenate values in R programming. Functions like paste and paste0 are used for that. It is good to know the difference between them.
Concatenate with function paste in R programming
The easiest way to concatenate in R is by using base function paste. If you have two values and you want space as a separator, it looks like this.
paste("Juliet", "James") # "Juliet James"
Space is the default separator. If you want a different separator, you can change it with the sep argument.
paste("Juliet", "James", sep = ", ") # "Juliet, James"
In the situation when it is necessary to concatenate a list of values, try collapse argument.
mynames <- c("Juliet", "James") paste(mynames, collapse = ", ") # "Juliet, James"
Sometimes it is good to know what is the paste0 function and what is difference between the paste function. Take a look below.
Concatenate with paste0 in R programming
If you want to concatenate elements without using a separator, then you can do that efficiently with paste0. By default, paste0 doesn’t use a separator. That is the difference between paste and paste0 in R.
In this example, you can see that you can get the same result as with the paste function but without additional argument.
paste0("Juliet", "James") # "JulietJames" paste("Juliet", "James", sep = "") # "JulietJames"
There are multiple scenarios where it might be an efficient way to concatenate in R. For example, by creating year and month combination or year and quarter combination.
If you want to use the paste or paste0 function in dplyr, one of the ways is to include that in mutate function.
require(dplyr) iris %>% mutate('cc' = paste0(Species, ", Sepal.Length: ", Sepal.Length)) %>% select(cc) %>% head() # cc #1 setosa, Sepal.Length: 5.1 #2 setosa, Sepal.Length: 4.9 #3 setosa, Sepal.Length: 4.7 #4 setosa, Sepal.Length: 4.6 #5 setosa, Sepal.Length: 5 #6 setosa, Sepal.Length: 5.4
Dplyr functionality is very useful when it comes to concatenating by a group.
Collapse argument in paste function in R
The collapse argument that is in the paste0 and the paste function in R has some interesting use cases. You can concatenate values by a group which means that you are concatenating by multiple rows.
For example, if you want to detect the combination of multiple strings, you can create a combination with the OR operator.
What about splitting in R?
Maybe you want to do the opposite of concatenation and split by a delimiter in R. Here is an example of how to split into columns and how to split into rows.
Leave a Reply