join/merge two columns inside a data-frame
Asked Answered
R

2

5

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
Reynold answered 28/11, 2012 at 1:12 Comment(0)
L
9

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
Licht answered 28/11, 2012 at 1:15 Comment(3)
what if we are dealing with empty values as well? how do we handle extra commasAlabaster
I am still waiting for your response. suppose the data is that col1 is blank and col2 has cat. wouldn't the resultant value be , cat. how to deal with that? I just need cat. the resultant could even be , , cat, , , dog if we are playing with multiple columnsAlabaster
@Alabaster The ifelse function should be what you're looking for. You might need several nested calls ifelse(..., ..., ifelse(...)) for multiple columns. For just one column that might be blank it would look like ifelse(df$col1 == "", df$col2, paste(df$col1, df$col2, sep=",")).Licht
B
2

If you want to leave them as a list of the two, (not a string concatenating both) then the following will work well

within(df, col3 <- Map(list, as.character(col1),as.character(col2)))  

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

Map is a simple wrapper for mapply(..., SIMPLIFY = FALSE)

Brambly answered 28/11, 2012 at 1:29 Comment(3)
Thanks, this looks interesting. I'll play around with it later.Reynold
what if we are dealing with empty values as well? how do we handle extra commasAlabaster
I am still waiting for your response. suppose the data is that col1 is blank and col2 has cat. wouldn't the resultant value be , cat. how to deal with that? I just need cat. the resultant could even be , , cat, , , dog if we are playing with multiple columnsAlabaster

© 2022 - 2024 — McMap. All rights reserved.