11.1 C
London
Sunday, July 7, 2024
HomeStatistics TutorialRHow to Use str_c in R (With Examples)

How to Use str_c in R (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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 #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 #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 #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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories