Search code examples
rmergecol

Merge two colums one to many in r


d1 = c("2a", "3a") 

d2 = c("k1", "k2")

Now, I need to create a column in a new vector say 'vec' as something like this:

vec = c("2a-k1", "2a-k2", "3a-k1", "3a-k2")

Basically I just need a column that has each combination from two columns. Merge option didnt help. Any advice is greatly appreciated.


Solution

  • I'm assuming a typo in your vec since you say " that has each combination from two columns". If so, then this should work

    x <- expand.grid(d1, d2, stringsAsFactors = FALSE)
    x$d3 <- paste(x[,"Var1"], x[,"Var2"], sep = "-")
    
    
    > x
      Var1 Var2    d3
    1   2a   k1 2a-k1
    2   3a   k1 3a-k1
    3   2a   k2 2a-k2
    4   3a   k2 3a-k2
    

    There are more elegant ways to do this using dplyr and such.