Programming
r
Updated Tue, 30 Aug 2022 20:33:56 GMT

Concatenate every two columns in dataframe


I have the following data frame:

X1   X2   X3   X4   X5   X6   X7
p1   H    I    K    J    K    H
p2   H    K    J    K    I    J
p3   J    K    H    I    J    K
p4   K    I    H    J    I    J

I want to create a new data frame with the column X1 and concatenate every two columns starting from X2 so the final table looks like:

X1   X2    X3    X4   
p1   HI    KJ    KH
p2   HK    JK    IJ
p3   JK    HI    JK
p4   KI    HJ    IJ



Solution

Using mapply:

cbind(df[ 1 ],
      mapply(paste0, df[, seq(2, 7, 2)], df[, seq(3, 7, 2)]))
#   X1 X2 X4 X6
# 1 p1 HI KJ KH
# 2 p2 HK JK IJ
# 3 p3 JK HI JK
# 4 p4 KI HJ IJ