Site icon R-bloggers

Little useless-useful R functions – Old phone converted from text to numbers

[This article was first published on R – TomazTsql, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

We all remember this, right?

What a nightmare was to type a short message on these keypads. So, image writing Hello on this keypad, you had to press: 4433555555666 to get the letters “hello”.

44 = h
33 = e
555 = l
555 = l
666 = o

So creating converter would be great to troll on your friends

By using this useless function, you can now convert text into numbers.

SMSconverter <- function(tt){
  st <- NULL
  tti <- unlist(strsplit(paste0(tt, " "), ""))
  # check if input string are letters
  if (!grepl("[^A-Za-z]", tti[1]) == TRUE){
    for (i in 1:nchar(tt)){
      lt <- substr(tt,i,i)
      if (lt != " "){
        rn <- substr(rownames(which(mm == lt, arr.ind = T)),2,2)
        rep <- which(mm == lt, arr.ind = T)[2]
        st <- c(st, replicate(rep, rn))
      } else { st <- c(st, "0") }
    }
    print(paste0(st, collapse = ""))
  }
  
  # check if input string are numbers
  if(!grepl("\\D", tti[1]) == TRUE){
    tti <- unlist(strsplit(paste0(tt, ""), ""))
    st <- NULL
    tti <- unlist(strsplit(as.character(tt), ""))
    tmp <- rle(tti)
    for (i in 1:length(tmp$lengths)){
      rpt <- tmp$lengths[i]
      row_cnt <- tmp$values[i]
      lt <- mm[as.integer(row_cnt)-1,rpt]
      st <- c(st, lt)  
    }
    print(paste(st, collapse=""))
  }
}

You can run the function as:

SMSconverter("text")

and it will output you the sequence of numbers, corresponding to the text: 833998.

The function is created to convert the text to numbers and numbers to text. Yet, the nondeterministic nature of numbers prevents correct conversion in the latter case.

Let me give you an example, with my name “tomaz”. The corresponding number conversion is 8666629999.

8 = t
6666 = can be: 6, 666 or 66, 66 or 666, 6 with solutions: m,o or nn or o,m
2 = a
9999 = z

So solutions can be tmoaz, tnnaz or tomaz. Well, one might need to use also the spell checker. Anyways, the conversion fails when there are multiple letters from the same key.

As always, complete code with helper datasets is available on Github in  Useless_R_function repository. The sample file in this repository is here (filename: Convert_text_to_number.R) Check the repository for future updates.

Happy R-coding and stay healthy!

To leave a comment for the author, please follow the link and comment on their blog: R – TomazTsql.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Exit mobile version