Reputation: 2154
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
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
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