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
REF:
http://www.cookbook-r.com/Manipulating_data/Reordering_the_columns_in_a_data_frame/
时间: 2024-10-12 13:21:34