Problem

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

Solution

# A sample data frame
data <- read.table(header=TRUE, text='
    id weight   size
     1     20  small
     2     27  large
     3     24 medium
')

# Reorder by column number
data[c(1,3,2)]
#>   id   size weight
#> 1  1  small     20
#> 2  2  large     27
#> 3  3 medium     24

# To actually change `data`, you need to save it back into `data`:
# data <- data[c(1,3,2)]


# Reorder by column name
data[c("size", "id", "weight")]
#>     size id weight
#> 1  small  1     20
#> 2  large  2     27
#> 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.

data[, c(1,3,2)]
#>   id   size weight
#> 1  1  small     20
#> 2  2  large     27
#> 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:

# List-style indexing of one column
data[2]
#>   weight
#> 1     20
#> 2     27
#> 3     24

# Matrix-style indexing of one column - drops dimension to become a vector
data[,2]
#> [1] 20 27 24

# Matrix-style indexing with drop=FALSE - preserves dimension to remain data frame
data[, 2, drop=FALSE]
#>   weight
#> 1     20
#> 2     27
#> 3     24