Here are 2 ways to concatenate the values of multiple columns into a new column in R DataFrame:
(1) Using the paste() function, including a separator between the concatenated values:
For example, to concatenate the values of 3 columns in a DataFrame, and form a new column called the concat_col, including an underscore (“_”) separator between the concatenated values:
df <- data.frame( col_1 = c("aa", "bb", "cc"), col_2 = c(11, 22, 33), col_3 = c("xx", "yy", "zz") ) df$concat_col <- paste(df$col_1, df$col_2, df$col_3, sep = "_") print(df)
Here is the new column with the concatenated values that include an underscore separator:
col_1 col_2 col_3 concat_col
1 aa 11 xx aa_11_xx
2 bb 22 yy bb_22_yy
3 cc 33 zz cc_33_zz
(2) Using the paste0() function, without a separator:
For example, to concatenate the values of 3 columns into a new column, excluding a separator:
df <- data.frame( col_1 = c("aa", "bb", "cc"), col_2 = c(11, 22, 33), col_3 = c("xx", "yy", "zz") ) df$concat_col <- paste0(df$col_1, df$col_2, df$col_3) print(df)
Here is the new column with the concatenated values without any separator:
col_1 col_2 col_3 concat_col
1 aa 11 xx aa11xx
2 bb 22 yy bb22yy
3 cc 33 zz cc33zz