Dan_yef Dan_yef - 1 year ago 71
R Question

Merging coulumns in data.frame with "/" symbol

For example, i have the following data.frame with 5 columns:

1 AAA 123 12 33 0.23
2 BBB 3123 44 22 0.55
3 CCC 221 45 11 0.44


From this data frame I want to create new, which looks like the following:

1 AAA 123/12 33/0.23
2 BBB 3123/44 22/0.55
3 CCC 221/45 11/0.44


How can I merge columns(2&3 and 4&5) with the separator "/"?

Of course the variables should be character.

Answer Source

We can loop through the second and fourth column index, get the columns based on the index and paste it together, and cbind with the first column of original dataset.

cbind(df[1], do.call(cbind, lapply(c(2,4), function(i) 
                   do.call(paste, c(df[i:(i+1)], sep="/")))))

Or another option is unite from tidyr

library(dplyr)
library(tidyr)
df %>%
    unite(col2_col3, col2, col3, sep="/") %>%
    unite(col4_col5, col4, col5, sep="/")