Home > Back-end >  Swap the first 2 columns in a data frame with 100 columns?
Swap the first 2 columns in a data frame with 100 columns?

Time:11-13

Is there a way to swap the order of the first 2 columns in a data frame with 100 columns?

All the methods online require you to input the order yourself and with 100 columns that's a bit too tedious.

Example solution being

dfrm <- dfrm[c("2", "3", "1", "4")]

However, with my large data frame this solution is impractical. I want to maintain all the columns order except swap the first two so column 2 is in column 1's position since the software I'm using requires column 1 to be sampleID which I have as column 2, which leads to an error.

Thanks

CodePudding user response:

You can consider the following. dfrm is your target data frame.

dfrm <- dfrm[, c(2, 1, 3:ncol(dfrm))]

Since 3:ncol(dfrm) maintains the same column index as the original data frame, this code will preserve all the column order except the first two columns.

CodePudding user response:

library(dplyr)
df <- tibble(a = c(2,3),
             b = c(3,4),
             c = c(9,9))

df <- df %>% relocate(b, .before = a)
df

CodePudding user response:

We could use select from dplyr package to put the first two columns by name and then use everything():

library(dplyr)
select(head(mtcars), cyl, disp, everything())
                  cyl disp  mpg  hp drat    wt  qsec vs am gear carb
Mazda RX4           6  160 21.0 110 3.90 2.620 16.46  0  1    4    4
Mazda RX4 Wag       6  160 21.0 110 3.90 2.875 17.02  0  1    4    4
Datsun 710          4  108 22.8  93 3.85 2.320 18.61  1  1    4    1
Hornet 4 Drive      6  258 21.4 110 3.08 3.215 19.44  1  0    3    1
Hornet Sportabout   8  360 18.7 175 3.15 3.440 17.02  0  0    3    2
Valiant             6  225 18.1 105 2.76 3.460 20.22  1  0    3    1

CodePudding user response:

data.table::setcolorder(dfrm, c(2, 1))

It doesn't even need to be a data.table.

  • Related