What is the unite() Function in R

The unite() function in R is “used to merge two or more columns into a single column or variable.”

Syntax

unite(data, col, ..., sep = ",", remove = TRUE)

Parameters

  1. data: It is a table or data frame.
  2. col: Name of a new column that is to be added.
  3. …: Names of columns that are to be united.
  4. sep: How to join the data in the columns.
  5. remove: Removes input columns from the output data frame; default = TRUE.

Return value

The unite() method returns a copy of the data frame with new columns.

Example 1: Unite Two Columns into One Column

library(tidyr)

# Sample data frame
df <- data.frame(
  first_name = c("John", "Jane", "Jim"),
  last_name = c("Doe", "Smith", "Brown"),
  age = c(30, 25, 27)
)

# Using unite() to combine first_name and last_name into a single column
df_united <- unite(df, "full_name", first_name, last_name, sep = " ")

print(df_united)

Output

   full_name    age
1  John Doe     30
2  Jane Smith   25
3  Jim Brown    27

Example 2: Unite More Than Two Columns

Here’s an example where we unite three columns:

library(tidyr)

# Sample data frame
df <- data.frame(
  first_name = c("John", "Jane", "Jim"),
  middle_name = c("Robert", "Marie", "Albert"),
  last_name = c("Doe", "Smith", "Brown"),
  age = c(30, 25, 27)
)

# Using unite() to combine first_name, middle_name,
# and last_name into a single column
df_united <- unite(df, "full_name", first_name, middle_name,
  last_name,
  sep = " "
)

print(df_united)

Output

    full_name          age
1  John Robert Doe     30
2  Jane Marie Smith    25
3  Jim Albert Brown    27

That’s it!

Related posts

gather() function in R

arrange() function in R

mutate() function in R

Leave a Comment