Skip to content

Instantly share code, notes, and snippets.

@dpmccabe
Last active May 30, 2018 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpmccabe/0661271c6acf9774b500f3a59c61b3e1 to your computer and use it in GitHub Desktop.
Save dpmccabe/0661271c6acf9774b500f3a59c61b3e1 to your computer and use it in GitHub Desktop.
course code sorting
library(dplyr)
library(tidyr)
library(stringr)
sort_course_codes <- function(course_codes) {
course_with_sorting <- data_frame(course_code = course_codes) %>%
mutate(course_code_cleaned = str_trim(tolower(str_replace_all(
course_code, "[(\\[\\{][^(\\[\\{]+[)\\]\\}]", ""
)))) %>%
separate(
course_code_cleaned,
into = c("alphnum_l", "alphnum_r"),
sep = "[-,[:space:]]",
extra = "merge",
fill = "right",
remove = F
) %>%
mutate(
num_l = as.numeric(str_extract(alphnum_l, "^[[:digit:]\\.]+")),
alph_l = str_replace(alphnum_l, "^[[:digit:]\\.]*", ""),
num_r = as.numeric(str_extract(alphnum_r, "^[[:digit:]\\.]+")),
alph_r = str_replace(alphnum_r, "^[[:digit:]\\.]*", "")
) %>%
replace_na(list(num_l = Inf, alph_l = "", num_r = Inf, alph_r = "")) %>%
arrange(num_l, alph_l, num_r, alph_r, course_code_cleaned, course_code)
course_with_sorting$course_code
}
course_codes = c(
"195", "106x", "241", "113-C", "123", "219", "104z", "143",
"104", "B", "159", "163", "163.2", "130x", "180", "20 [x-reg]",
"185", "150", "158", "212", "121a", "A-26", "A-30", "200.01"
)
sorted_course_codes <- sort_course_codes(course_codes)
invisible(sapply(sorted_course_codes, message))
20 [x-reg]
104
104z
106x
113-C
121a
123
130x
143
150
158
159
163
163.2
180
185
195
200.01
212
219
241
A-26
A-30
B
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment