tubby
tubby

Reputation: 2154

re-arrange columns in a data frame in R

I have a script which refers to certain columns by indices and not names. Is there a way for a new data set which has the same columns to be re-arranged in a way that in would fit the original data frame for which the script was written?

I would like df2 to have the same order of columns as df1 below

age = c(20,30,22,32,10)
gender = c('M','F','M','F','M')
name = c('A','B','C','D','E')

df1 = data.frame(age,name,gender)
df2 = data.frame(gender, name, age)
> df1
  age name gender
1  20    A      M
2  30    B      F
3  22    C      M
4  32    D      F
5  10    E      M
> df2
  gender name age
1      M    A  20
2      F    B  30
3      M    C  22
4      F    D  32
5      M    E  10

Upvotes: 2

Views: 135

Answers (3)

MichaelChirico
MichaelChirico

Reputation: 34763

If you decide to start using the data.table package, there is a setcolorder function that works like so:

setcolorder(df2,names(df1))

From ?setcolorder:

setcolorder reorders the columns of data.table, by reference, to the new order provided.

You can read more about what's mean by "by reference" here, but suffice to say you should prefer this if you've got a large data.frame because it will be faster.

Upvotes: 2

Jilber Urbina
Jilber Urbina

Reputation: 61214

> df2[, names(df1)]
  age name gender
1  20    A      M
2  30    B      F
3  22    C      M
4  32    D      F
5  10    E      M

Upvotes: 2

akrun
akrun

Reputation: 887741

You can just do

 df2[names(df1)]

Upvotes: 5

Related Questions