Seems like a pretty basic question, but I can't really figure out an "easy" way to do it.
I'd like to sort a character
vector containing semantic version numbers with base R functionality:
vsns <- c("1", "10", "1.1", "1.10", "1.2", "1.1.1",
"1.1.10", "1.1.2", "1.1.1.1", "1.1.1.10", "1.1.1.2")
It should look like this after sorting:
# [1] "1" "1.1" "1.1.1" "1.1.1.1" "1.1.1.2" "1.1.1.10"
# [7] "1.1.2" "1.1.10" "1.2" "1.10" "10"
This doesn't get me what I want, of cours, as R simply sorts the whole thing alphabetically:
sort(vsns)
# [1] "1" "1.1" "1.1.1" "1.1.1.1" "1.1.1.10" "1.1.1.2" "1.1.10"
# [8] "1.1.2" "1.10" "1.2" "10"
vsns[order(vsns)]
# [1] "1" "1.1" "1.1.1" "1.1.1.1" "1.1.1.10" "1.1.1.2" "1.1.10"
# [8] "1.1.2" "1.10" "1.2" "10"
Trying normalizing it (somewhat along this post), but I can't think of a matching/substitution scheme that would fit the structure of semantic versions:
tmp <- gsub("\\.", "", vsns)
# [1] "011" "021" "0101" "0201"
tmp_nchar <- sapply(tmp, nchar)
to_add <- max(tmp_nchar) - tmp_nchar
tmp <- sapply(1:length(tmp), function(ii) {
paste0(tmp[ii], paste(rep("A", to_add[ii]), collapse = ""))
})
# [1] "10" "1.10" "1.1.10" "1.1.1.10" "1.1.1.1" "1.1.1.2" "1.1.1"
# [8] "1.1.2" "1.1" "1.2" "1"
vsns[order(tmp)]
# [1] "1AAAA" "10AAA" "11AAA" "110AA" "12AAA" "111AA" "1110A" "112AA" "1111A" "11110"
# [11] "1112A"
The best I could come up with so far is this, but it seems pretty... Involved ;-)
sortVersionNumbers <- function(x, decreasing = FALSE) {
tmp <- strsplit(x, split = "\\.")
tmp_l <- sapply(tmp, length)
idx_max <- which.max(tmp_l)[1]
tmp_l_max <- tmp_l[idx_max]
tmp_n <- lapply(tmp, function(ii) {
ii_l <- length(ii)
if (ii_l < tmp_l_max) {
c(ii, rep(NA, (tmp_l_max - ii_l)))
} else {
ii
}
})
tmp <- matrix(as.numeric(unlist(tmp_n)), nrow = length(tmp_n), byrow = TRUE)
tmp_cols <- ncol(tmp)
expr <- paste0("order(", paste(paste0("tmp[,", 1:tmp_cols, "]"),
collapse = ", "), ", na.last = FALSE",
ifelse(decreasing, ", decreasing = FALSE)", ")"))
idx <- eval(parse(text = expr))
tmp_2 <- tmp[idx,]
sapply(1:nrow(tmp_2), function(ii) {
paste(na.omit(tmp_2[ii,]), collapse = ".")
})
}
sortVersionNumbers(vsns)
# [1] "1" "1.1" "1.1.1" "1.1.1.1" "1.1.1.2" "1.1.1.10" "1.1.2"
# [8] "1.1.10" "1.2" "1.10" "10"
sortVersionNumbers(sort(vsns))
# [1] "1" "1.1" "1.1.1" "1.1.1.1" "1.1.1.2" "1.1.1.10" "1.1.2"
# [8] "1.1.10" "1.2" "1.10" "10"