Search code examples
rdplyrmergemultiple-columns

Create a new categorical column merging two categorical columns


I have this df

df <- data.table(id=c(1,2,3,4,5,6,7,8,9,10),
                 var1=c(0,4,5,6,99,3,5,5,23,0),
                 var2=c(22,4,6,25,6,70,75,23,24,21))

I would like to create a third column being:

df <- data.table(id=c(1,2,3,4,5,6,7,8,9,10),
                 var1=c(0,4,5,6,99,3,5,5,23,0),
                 var2=c(22,4,6,25,6,70,75,23,24,21),
                 var3=c("0_22","4_4","5_6","6_25","99_6","3_70","5_75","5_23","23_24","0_21"))

where the value of each cell will be "var1 underscore var2". Var1 and Var2 are categorical variables as they represent medications. Var3 would be to represent a combination of medications.

how can I do this?

thanks!


Solution

  • as @Wimpel says, the solution is df$var3 <- paste(df$var1, df$var2, sep = "_") thanks!!