Reordering the columns in a data frame

Problem

You want to do reorder the columns in a data frame.

Solution

  1. # A sample data frame
  2. data <- read.table(header=TRUE, text='
  3. id weight size
  4. 1 20 small
  5. 2 27 large
  6. 3 24 medium
  7. ')
  8. # Reorder by column number
  9. data[c(1,3,2)]
  10. #> id size weight
  11. #> 1 1 small 20
  12. #> 2 2 large 27
  13. #> 3 3 medium 24
  14. # To actually change `data`, you need to save it back into `data`:
  15. # data <- data[c(1,3,2)]
  16. # Reorder by column name
  17. data[c("size", "id", "weight")]
  18. #> size id weight
  19. #> 1 small 1 20
  20. #> 2 large 2 27
  21. #> 3 medium 3 24

The above examples index into the data frame by treating it as a list (a data frame is essentially a list of vectors). You can also use matrix-style indexing, as in data[row, col], where row is left blank.

  1. data[, c(1,3,2)]
  2. #> id size weight
  3. #> 1 1 small 20
  4. #> 2 2 large 27
  5. #> 3 3 medium 24

The drawback to matrix indexing is that it gives different results when you specify just one column. In these cases, the returned object is a vector, not a data frame. Because the returned data type isn’t always consistent with matrix indexing, it’s generally safer to use list-style indexing, or the drop=FALSE option:

  1. # List-style indexing of one column
  2. data[2]
  3. #> weight
  4. #> 1 20
  5. #> 2 27
  6. #> 3 24
  7. # Matrix-style indexing of one column - drops dimension to become a vector
  8. data[,2]
  9. #> [1] 20 27 24
  10. # Matrix-style indexing with drop=FALSE - preserves dimension to remain data frame
  11. data[, 2, drop=FALSE]
  12. #> weight
  13. #> 1 20
  14. #> 2 27
  15. #> 3 24