Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reorder few columns only out of hundreds

Tags:

r

What is the most efficient way to reorder columns for data frames with hundreds even thousands of columns?

The following is tried and it works, however I am looking for an optimal function.

dput(names(df1)) to dump all column names and used in the following step

swapped columns with df1[c(col1, col3, col2,.....col99,col100)

ex names(df1)
"col1" "col2" "col3".............."col99" "col100"

Want to swap only "col2" and "col3", with

names(df1)
"col1" "col3" "col2".............."col99" "col100"
like image 886
Antex Avatar asked Dec 29 '25 22:12

Antex


1 Answers

df1 = df1[,c(1,3,2,4:100)]

reorders your columns according to the permutation c(1,3,2,4:100)

like image 110
mts Avatar answered Jan 01 '26 11:01

mts