Unite - dsofe/coderr GitHub Wiki

Unite()

create new var by concatenating other vars

# unite, or concatenate, values across columns

df <- starwars

df1 <- df %>%
  select(name:species)


# don't ignore NAs
df2.1 <- df1 %>%
  unite("homeworld_species", c(homeworld, species), sep = "_", remove = FALSE)   
# don't need quotation marks for NEWVAR: homeworld_species and "homeworld_species" work precisely the same
# "NA" retained, so value may be "NA_something" or "Something_NA"

# ignore NAs
df2.2 <- df1 %>%
  unite("homeworld_species", c(homeworld, species), na.rm = TRUE, sep = "_", remove = FALSE)
# "NA" removed, so single homeworld or species or neither (thus, blank string/value/cell) remains


# concatenate numeric and string
df3.1 <- df1 %>%
  unite("height_species", c(height, species), sep = "_", na.rm = TRUE, remove = FALSE)
# "NA" removed, so single homeworld or species or neither (thus, blank string/value/cell) remains

df3.2 <- df1 %>%
  unite(height_species, c(height, species), sep = "_", na.rm = TRUE, remove = FALSE)
# "NA" removed, so single homeworld or species or neither (thus, blank string/value/cell) remains
⚠️ **GitHub.com Fallback** ⚠️