Graphics Reference
In-Depth Information
"Angle"
"Experimental" "Control"
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