tidyr::unite()
get_help()
docs
The unite()
function is part of the {tidyr}
package, which is part of the {tidyverse}
.
We use unite()
to combine two columns in a tibble (data frame) into a single columns. By default, column values are united with an underscore (_
), but this can be changed with the sep
argument.
To use this function, you need to either first load the {tidyr}
library, or always use the function with tidyr::unite()
notation.
# Load the library
library(tidyr)
# Or, load the full tidyverse:
library(tidyverse)
# Or, use :: notation
::unite() tidyr
%>%
tibble unite(name of new column,
first column to unite,
second column to unite)
%>%
tibble unite(name of new column,
first column to unite,
second column to unite, sep = "optional character saying how to unite the values")
All examples use this dataset, which contains some names of notable biologists:
biologists
## # A tibble: 3 × 2
## first_name last_name
## <chr> <chr>
## 1 Rosalind Franklin
## 2 Lynn Margulis
## 3 Barbara McClintock
# Combine `first_name` and `last_name` into `full_name`
%>%
biologists unite(full_name, first_name, last_name)
## # A tibble: 3 × 1
## full_name
## <chr>
## 1 Rosalind_Franklin
## 2 Lynn_Margulis
## 3 Barbara_McClintock
# Combine `first_name` and `last_name` into `full_name`, and KEEP the two originals
%>%
biologists unite(full_name, first_name, last_name,
remove = FALSE)
## # A tibble: 3 × 3
## full_name first_name last_name
## <chr> <chr> <chr>
## 1 Rosalind_Franklin Rosalind Franklin
## 2 Lynn_Margulis Lynn Margulis
## 3 Barbara_McClintock Barbara McClintock
# Combine `first_name` and `last_name` into `full_name`,
# but separate with a space instead of underscore
%>%
biologists unite(full_name, first_name, last_name,
sep = " ")
## # A tibble: 3 × 1
## full_name
## <chr>
## 1 Rosalind Franklin
## 2 Lynn Margulis
## 3 Barbara McClintock
# Combine `first_name` and `last_name` into `full_name_reverse`, a different format
# Note the order of arguments and the separator used
%>%
biologists unite(full_name_reverse, last_name, first_name,
sep = ", ")
## # A tibble: 3 × 1
## full_name_reverse
## <chr>
## 1 Franklin, Rosalind
## 2 Margulis, Lynn
## 3 McClintock, Barbara