How to Use str_c() Function in R

The str_c() function from the stringr package in R is “used to combine two or more vectors element-wise into a single character vector”.

Syntax

str_c(..., sep = "", collapse = NULL)

Parameters

  1. . . .: One or more character vectors.
  2. sep: String to insert between vectors.
  3. collapse: It is an optional string that combines output into a single string.

Return value

The return value of the str_c() function is a string or a vector of strings, depending on the input.

Example 1: Using str_c() function with No Separator

library(stringr)

# example usage of str_c() with no separator
string1 <- "Homer"
string2 <- "Simpson"
combined_string <- str_c(string1, string2, sep = "")

# print the combined string
print(combined_string)

Output

[1] "HomerSimpson"

Example 2: Using str_c() function with Separator

You can use the str_c() function to “combine two vectors element-wise into a single character vector with an underscore as a separator”.

library(stringr)

# example usage of str_c() with _ as a separator
string1 <- "Homer"
string2 <- "Simpson"
combined_string <- str_c(string1, string2, sep = "_")

# print the combined string
print(combined_string)

Output

[1] "Homer_Simpson"

Example 3: Using str_c() function with collapse option

The “collapse” argument in the str_c() function is used when you have a vector of strings you want to combine into a single string, with a specified separator between each element.

library(stringr)

# example usage of str_c() with collapse argument
string_vector <- c("Hello", "World", "This", "Is", "R")
combined_string <- str_c(string_vector, collapse = " ")

# print the combined string
print(combined_string)

Output

[1] "Hello World This Is R"

That’s it!

Leave a Comment