How to stop tidyr spread sorting columns alphabetically
You can use dplyr::select()
after tidyr::spread()
to preserve the original column order. Note your rows may still be alphabetically sorted.
library(tidyverse)
mtcars <- rownames_to_column(mtcars, "vehicle")
colnames(mtcars)
# [1] "vehicle" "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear" "carb"
Regular spread behavior with alphabetically arranged column order:
spreadMtcarsSorted <- gather(mtcars, measure, value, -vehicle) %>%
spread(measure, value)
colnames(spreadMtcarsSorted)
# [1] "vehicle" "am" "carb" "cyl" "disp" "drat" "gear" "hp" "mpg" "qsec" "vs" "wt"
Reverting to original column order after the spread operation:
spreadMtcarsOriginalColOrder <- gather(mtcars, measure, value, -vehicle) %>%
spread(measure, value) %>%
select(colnames(mtcars)) # use original column order before returning new data frame
colnames(spreadMtcarsOriginalColOrder)
# [1] "vehicle" "mpg" "cyl" "disp" "hp" "drat" "wt" "qsec" "vs" "am" "gear" "carb"