Search code examples
rcopycolumnsorting

Duplicating a column and placing right next to that duplicated column


I want to duplicate a column, but all the examples I see has the duplicated column go right at the end of the data frame, but I want it right next to what was duplicated instead, and push the rest of the data down instead.

For example: I have DF1

Name Key BCD12A ACA1 DEX2
X_1_group1 test1234 10 10 8
X_2_group1 test4553 8 7 4
X_2_group2 test3341 5 5 5
X_2_group1 test2142 5 6 8
X_1_group2 test4722 6 7 4

Duplicating this, I would have another column that copies"DF$Key" right after the second column. Any suggestions on doing this would be appreciated!

# DF1
Name <- c("X_1_group1", "X_2_group1", "X_2_group2", "X_2_group1", "X1_group2")
Key <- c("test1234", "test4553", "test3341", "test2142", "test4722")
BCD12A <- c(10, 8, 5, 5, 6)
ACA1 <- c(10, 7, 5, 6, 7)
DEX2 <- c(8, 4, 5, 8, 4)
DF1 <- data.frame(Name, Key, BCD12A, ACA1, DEX2)

Solution

  • We may use mutate with .after or .before to create the column. The input to .after/.before can be either unquoted/quoted column name or numeric column index

    library(dplyr)
    DF1 <- DF1 %>% 
         mutate(Key2 = Key, .after = Key)
    

    -output

    DF1
            Name      Key     Key2 BCD12A ACA1 DEX2
    1 X_1_group1 test1234 test1234     10   10    8
    2 X_2_group1 test4553 test4553      8    7    4
    3 X_2_group2 test3341 test3341      5    5    5
    4 X_2_group1 test2142 test2142      5    6    8
    5 X_1_group2 test4722 test4722      6    7    4