1

suppose I like to map any combination of string of length k into integers (if count only 26 latters uppers and lowers I will have (26+26) ^k combination. Is there a fast way in r to map, given string of length k into unique integer?

For example: 1. Say for k=1 and c("a","d","z"), then the result will be c(1,4,26). 2. Say for k=2 and c("aa","da","zA"), then the result will be c(53,157,1379).

6
  • 1
    If you had 16 letters your question would be equivalent to how to transform hexadecimal numbers to decimal numbers. Your base is 52, but the same algorithms can be used. Commented Nov 13, 2014 at 14:03
  • I have a string of length k, when k is large (say 10), I need a fast method to map it to an integer. I don't know in advance the string to map, only the fixed length of k. Commented Nov 13, 2014 at 14:09
  • I've just told you a fast way. Commented Nov 13, 2014 at 14:13
  • For a start you should study this: en.wikipedia.org/wiki/Hexavigesimal Commented Nov 13, 2014 at 14:16
  • How can I treat a string as a number in say 52 base? Do you know a function that tack string and convert it to number in some base? What about the other symbols like "?",":"," ","!" and so on? Commented Nov 13, 2014 at 14:17

1 Answer 1

3
conv <- function(strings, base = letters) {
  s <- strsplit(strings, "") 
  vapply(s, function(x, base) {
    x <- match(x, base)
    as.integer(t(x) %*% (length(base)^(rev(seq_along(x)) - 1L)))
  }, 1L, base=base)
}

#test it
strtoi("5A3", base=16)
#[1] 1443
conv("5A3", base=c(1:9, LETTERS[1:7]))
#[1] 1443

mystring <- c("a", "d", "z", "aa","da","zA")
conv(mystring, base = c(letters, LETTERS))
#[1]    1    4   26   53  209 1379

Other symbols can be included easily in the base parameter.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.