Skip to content

Instantly share code, notes, and snippets.

@xenatisch
Created January 5, 2023 12:40
Show Gist options
  • Save xenatisch/1c57003fe031cd1df64af525d9232e44 to your computer and use it in GitHub Desktop.
Save xenatisch/1c57003fe031cd1df64af525d9232e44 to your computer and use it in GitHub Desktop.
Convert non-decimal integer numbers as string to decimal integers in R
# Examples:
# to_decimal("83", 12) : 44
# to_decimal("01101", 2) : 22
to_decimal <- function(num, base) {
digits <- strsplit(num, "")[[1]]
value <- 0
sequence <- seq_along(digits)
for ( ind in sequence[rev(sequence)] ) {
current <- as.integer(digits[ind]) * base ^ (ind - 1)
value <- value + current
}
return(value)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment