Search code examples
rmultiple-columnsswap

Swap multiple column in R


SUppose I have a data frame

data=data.frame(X1_C1=c(1:5),
                X2_C1=c(11:15),
                X3_C1=c(111:115),
                X1_C2=c(2:6),
                X2_C2=c(21:25),
                X3_C2=c(211:215),
                X1_C3=c(3:7),
                X2_C3=c(31:35),
                X3_C3=c(311:315))


> data
  X1_C1 X2_C1 X3_C1 X1_C2 X2_C2 X3_C2 X1_C3 X2_C3 X3_C3
1     1    11   111     2    21   211     3    31   311
2     2    12   112     3    22   212     4    32   312
3     3    13   113     4    23   213     5    33   313
4     4    14   114     5    24   214     6    34   314
5     5    15   115     6    25   215     7    35   315

I would like to swap the value so columns in variable ending with _C2 and _C3. For example, swap X1_C2 and X1_C3, X2_C2 and X2_C3 and similar for other Xs in C2 and C3

Any help in appreciated


Solution

  • If you want to swap columns (not just the names), you can try the code below

    > data[c(matrix(names(data), 3)[, c(1, 3, 2)])]
      X1_C1 X2_C1 X3_C1 X1_C3 X2_C3 X3_C3 X1_C2 X2_C2 X3_C2
    1     1    11   111     3    31   311     2    21   211
    2     2    12   112     4    32   312     3    22   212
    3     3    13   113     5    33   313     4    23   213
    4     4    14   114     6    34   314     5    24   214
    5     5    15   115     7    35   315     6    25   215
    

    If you want to swap the names

    > setNames(data, c(matrix(names(data), 3)[, c(1, 3, 2)]))
      X1_C1 X2_C1 X3_C1 X1_C3 X2_C3 X3_C3 X1_C2 X2_C2 X3_C2
    1     1    11   111     2    21   211     3    31   311
    2     2    12   112     3    22   212     4    32   312
    3     3    13   113     4    23   213     5    33   313
    4     4    14   114     5    24   214     6    34   314
    5     5    15   115     6    25   215     7    35   315