Alexis Begni
Alexis Begni

Reputation: 106

Merging two column name in an another one

I'm trying to merge to column name to create another one, Here is below, some data of what I'm trying to do. Thanks for the help


Bloc <- c("LE3", "LE5", "LE2", "LE5", "LE6")
Id <- c(69, 66, 71, 72, 76)
df1 <- data.frame(Bloc, Id)


Bloc <- c("LE3", "LE5", "LE2", "LE5", "LE6")
Id <- c(69, 66, 71, 72, 76)
Name <- c("LE3-69", "LE5-66", "LE2-71", "LE5-72", "LE6-76")
df2 <-  data.frame(Bloc, Id, Name)

Upvotes: 1

Views: 29

Answers (1)

akrun
akrun

Reputation: 887148

We can use paste in base R

df1$Name <- paste(df1$Bloc, df1$Id, sep="-")

If there are many columns, we can also do

df1$Name <- do.call(paste, c(df1, sep="-"))

Or with unite from tidyr

library(dplyr)
library(tidyr)
df1 %>%
   unite(Name, Bloc, Id, sep="-", remove = FALSE)  %>%
   select(names(df1), Name)
#  Bloc Id   Name
#1  LE3 69 LE3-69
#2  LE5 66 LE5-66
#3  LE2 71 LE2-71
#4  LE5 72 LE5-72
#5  LE6 76 LE6-76

Upvotes: 1

Related Questions