简体   繁体   English

重新安排R中数据框中的列

[英]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 我希望df2与下面的df1具有相同的列顺序

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: 如果您决定开始使用data.table包,则有一个setcolorder函数,其工作方式如下:

setcolorder(df2,names(df1))

From ?setcolorder : 来自?setcolorder

setcolorder reorders the columns of data.table, by reference, to the new order provided. setcolorder通过引用将data.table列重新排序到提供的新订单。

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. 您可以了解更多关于什么是平均的“参照” 在这里 ,但我只想说,你应该更喜欢这个,如果你已经有了一个大的 data.frame ,因为它会更快。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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