Opposite of tidyr::separate, concatenating multiple columns into one

You can use the unite function from tidyr:

library(tidyr)
unite(df, string, X1:X5, sep = ", ")
#  id            string
#1  1  W4, L, 1, H7, J8
#2  2 W5, O1, 2, NA, NA
#3  3 49, P6, 10, K, NA

Note that it also has a remove argument that is TRUE by default. If you set it to FALSE, the original columns are kept in the data.

For the column specification (which columns to unite) you can use the colon operator (:) as I did above or use the special functions described in ?dplyr::select.


We can do this in base R without any packages

data.frame(id = df[1], string= do.call(paste, c(df[-1], sep=",")))
#  id        string
#1  1  W4,L,1,H7,J8
#2  2 W5,O1,2,NA,NA
#3  3 49,P6,10,K,NA

Tags:

R

Dplyr

Tidyr