简体   繁体   中英

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

你可以这样做

 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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM