Okay, I know that fct_reorder()
lets you reorder factors based on another column, but from what I can tell, you have to supply some function (mean, median, etc.) that operates on the second column for it to know how to order the columns. But what if you have another column that sorts the way you want your column to be leveled/ordered as is?
For instance, I have a column ACADEMIC_PERIOD_DESC
that gives the academic period in English: "Fall 2019," "Spring 2020," etc., and I have a corresponding column, ACADEMIC_PERIOD
, that is a numeric code corresponding to the academic period: "201940," "202020," etc. This is the column I want ACADEMIC_PERIOD_DESC
to be leveled by.
Data
df <- structure(list(ACADEMIC_PERIOD = c("200810", "200820", "200830",
"200840", "200910", "200920", "200930", "200940", "201010", "201020"
), ACADEMIC_PERIOD_DESC = structure(1:10, .Label = c("J-Term 2008",
"Spring 2008", "Summer 2008", "Fall 2008", "J-Term 2009", "Spring 2009",
"Summer 2009", "Fall 2009", "J-Term 2010", "Spring 2010", "Summer 2010",
"Fall 2010", "J-Term 2011", "Spring 2011", "Summer 2011", "Fall 2011",
"J-Term 2012", "Spring 2012", "Summer 2012", "Fall 2012", "J-Term 2013",
"Spring 2013", "Summer 2013", "Fall 2013", "Spring 2014", "Summer 2014",
"Fall 2014", "J-Term 2015", "Spring 2015", "Summer 2015", "Fall 2015",
"J-Term 2016", "Spring 2016", "Summer 2016", "Fall 2016", "J-Term 2017",
"Spring 2017", "Summer 2017", "Fall 2017", "J-Term 2018", "Spring 2018",
"Summer 2018", "Fall 2018", "J-Term 2019", "Spring 2019", "Summer 2019",
"Fall 2019", "J-Term 2020", "Spring 2020"), class = "factor")), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -10L))
Should I just do the following even though it is unnecessarily applying the median?
df %>%
mutate(ACADEMIC_PERIOD_DESC = fct_reorder(ACADEMIC_PERIOD_DESC, as.integer(ACADEMIC_PERIOD)))
I also know I can just use base R like this:
df$ACADEMIC_PERIOD_DESC <- reorder(df$ACADEMIC_PERIOD_DESC, df$ACADEMIC_PERIOD)
Is there a more elegant forcats/tidyverse solution? Am I just missing something?
Thanks!