Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

15. Getting Your Data into Shape > Reordering Columns in a Data Frame

Reordering Columns in a Data Frame

Problem

You want to change the order of columns in a data frame.

Solution

To reorder columns by their numeric position:

dat <- dat[c(1,3,2)]

To reorder by column name:

dat <- dat[c("col1", "col3", "col2")]

Discussion

The previous examples use list-style indexing. A data frame is essentially a list of vectors, and indexing into it as a list will return another data frame. You can get the same effect with matrix-style indexing:

library(gcookbook) # For the data set
anthoming

 angle expt ctrl
   -20    1    0
   -10    7    3
     0    2    3
    10    0    3
    20    0    1

anthoming[c(1,3,2)]     # List-style indexing

 angle ctrl expt
   -20    0    1
   -10    3    7
     0    3    2
    10    3    0
    20    1    0

# Putting nothing before the comma means to select all rows
anthoming[, c(1,3,2)]   # Matrix-style indexing

 angle ctrl expt
   -20    0    1
   -10    3    7
     0    3    2
    10    3    0
    20    1    0

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint