Created
January 5, 2023 12:40
-
-
Save xenatisch/1c57003fe031cd1df64af525d9232e44 to your computer and use it in GitHub Desktop.
Convert non-decimal integer numbers as string to decimal integers in R
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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