join/merge two columns inside a data-frame

Eric Fail picture Eric Fail · Nov 28, 2012 · Viewed 9.7k times · Source

Say I have this data,

(df <- data.frame( col1 = c('My','Your','His','Thir'), col2 = c('Cat','Dog','Fish','Dog')))

  col1 col2
1   My  Cat
2 Your  Dog
3  His Fish
4 Thir  Dog

and I want to combine the columns like this

`some magic`

  col1 col2      col3
1   My  Cat    My Cat
2 Your  Dog  Your Dog
3  His Fish  His Fish
4 Thir  Dog  Thir Dog

What do I do? maybe even with a comma (,) like this,

`some magic`

  col1 col2      col3
1   My  Cat    My, Cat
2 Your  Dog  Your, Dog
3  His Fish  His, Fish
4 Thir  Dog  Thir, Dog

Answer

Erik Shilts picture Erik Shilts · Nov 28, 2012

df$col3 <- paste(df$col1, df$col2, sep=","). You can also use the sprintf and paste0 functions.

df$col3 <- paste(df$col1, df$col2, sep=",") # comma separator
df$col3 <- paste0(df$col1, df$col2) # for no separator