How to Use str_c in R (With Examples)


The str_c() function from the stringr package in R can be used to join two or more vectors element-wise into a single character vector.

This function uses the following syntax:

str_c(. . ., sep = “”)

where:

  • . . .: One or more character vectors
  • sep: String to insert between vectors

The following examples show how to use this function in practice

Example 1: Use str_c with No Separator

The following code shows how to use the str_c() function to join together two vectors element-wise into a single character vector:

library(stringr)

#define two vectors
vec1 <- c('Mike', 'Tony', 'Will', 'Chad', 'Rick')
vec2 <- c('Douglas', 'Atkins', 'Durant', 'Johnson', 'Flair')

#join vectors together element-wise
str_c(vec1, vec2)

[1] "MikeDouglas" "TonyAtkins"  "WillDurant"  "ChadJohnson" "RickFlair"  

The result is a single character vector.

Note that the vectors have been joined together element-wise with no separator between the elements.

Example 2: Use str_c with Separator

The following code shows how to use the str_c() function to join together two vectors element-wise into a single character vector with an underscore as a separator:

library(stringr)

#define two vectors
vec1 <- c('Mike', 'Tony', 'Will', 'Chad', 'Rick')
vec2 <- c('Douglas', 'Atkins', 'Durant', 'Johnson', 'Flair')

#join vectors together element-wise
str_c(vec1, vec2, sep="_")

[1] "Mike_Douglas" "Tony_Atkins"  "Will_Durant"  "Chad_Johnson" "Rick_Flair"    

The result is a single character vector in which the elements from each vector have been joined with an underscore.

Feel free to use any character you’d like for the sep argument.

For example, you may choose to use a dash:

library(stringr)

#define two vectors
vec1 <- c('Mike', 'Tony', 'Will', 'Chad', 'Rick')
vec2 <- c('Douglas', 'Atkins', 'Durant', 'Johnson', 'Flair')

#join vectors together element-wise
str_c(vec1, vec2, sep="-")

[1] "Mike-Douglas" "Tony-Atkins"  "Will-Durant"  "Chad-Johnson" "Rick-Flair"  

The result is a single character vector in which the elements from each vector have been joined with a dash.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Use str_replace in R
How to Use str_split in R
How to Use str_detect in R

Leave a Reply

Your email address will not be published.