use mutate to unite two columns in r

To unite two columns in R using the mutate function from the dplyr package along with the unite function from the tidyr package, you can use the following code:

main.r
# Install and load necessary libraries
# install.packages(c("dplyr", "tidyr"))
library(dplyr)
library(tidyr)

# Create a sample dataframe
df <- data.frame(
  col1 = c("a", "b", "c"),
  col2 = c("x", "y", "z")
)

# Unite two columns
df_united <- df %>% 
  unite("new_col", col1, col2, sep = "_")

# Print the united dataframe
print(df_united)
342 chars
18 lines

However, unite is actually a function from the tidyr package. If you want to use mutate to unite two columns, you can use the paste function or str_c from the stringr package:

main.r
# Install and load necessary libraries
# install.packages(c("dplyr", "stringr"))
library(dplyr)
library(stringr)

# Create a sample dataframe
df <- data.frame(
  col1 = c("a", "b", "c"),
  col2 = c("x", "y", "z")
)

# Unite two columns using mutate
df_united <- df %>% 
  mutate(new_col = str_c(col1, col2, sep = "_"))

# Print the united dataframe
print(df_united)
366 chars
18 lines

Or using paste:

main.r
# Create a sample dataframe
df <- data.frame(
  col1 = c("a", "b", "c"),
  col2 = c("x", "y", "z")
)

# Unite two columns using mutate
df_united <- df %>% 
  mutate(new_col = paste(col1, col2, sep = "_"))

# Print the united dataframe
print(df_united)
252 chars
13 lines

related categories

gistlibby LogSnag