1

If I have variables in a data frame in the following order

date var1 var2 var3

is there a way to rearrange the variables so that visually when I see the data using the View(data) or fix(data) command, I can see them rearranged in the following

date var2 var3 var1

jessica
  • 1,325
  • 2
  • 21
  • 35

2 Answers2

2

If you have a data.frame named df with names(df) as c('date', 'V1', 'V2', 'V3'), you can reorder it to c('date', 'V2', 'V3', 'V1') using this:

df <- df[,c(1,3,4,2)]
JBecker
  • 804
  • 6
  • 9
1

I think in your example I would probably go with @JBecker's answer, but I'd like to bring to your attention 'DataCombine' , a nice little package with all sorts of tools regarding data cleaning, combining etc. The function 'MoveFront' would do what you want.

require(DataCombine)
# using 'OldOrder' as the name of the original df
NewOrder <- MoveFront(OldOrder, c('date', 'V2', 'V3'))`
hvollmeier
  • 2,956
  • 1
  • 12
  • 17
  • You may also check out [my post here](http://stackoverflow.com/questions/12544888/is-there-an-equivalent-r-function-to-stata-order-command) or [at my blog](http://news.mrdwab.com/2013/08/28/an-r-function-like-order-from-stata/) where I introduce a function called "`moveme`" that works nicely to help rearrange columns in a `data.frame`. – A5C1D2H2I1M1N2O1R2T1 Dec 09 '13 at 10:25