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
You can just do
df2[names(df1)]
> 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With