How can you reverse a string of numbers in R?
for instance, I have a vector of about 1000 six digit numbers, and I would like to know if they are palindromes. I would like to create a second set which is the exact reverse, so I could do a matchup.
To get started, let’s generate a random string of 10 million DNA bases (we can do this with the stringi package as well, but for our purposes here, let’s just use base R functions). One way to reverse a string is to use strsplit with paste. This is the slowest method that will be shown, but it does get the job done without needing any packages.
Sometimes the vector values are recorded in the reverse order in R, therefore, we need to again reverse those vectors to get the actual order we want. For example, a sequence of numbers might be recorded as 1 to 20 but we wanted it to be from 20 to 1.
It shows that our example data is a vector of character strings containing three elements. In this section, I’ll explain how to reverse the ordering of the characters in our vector of strings using the basic installation of the R programming language. For this, we have to use the sapply, lapply, strsplit, and rev functions as shown below:
The sprintf R function also provides the possibility to control decimal places of a certain number or a numeric vector. Let’s have a look at the R syntax: The output is the same as before.
It is actually the decimial representation of the number that you are testing to be a palindrome, not the number itself (255 is a palendrome in hex and binary, but not decimal).
You can do this fairly simply using pattern matching:
> tmp <- c(100001, 123321, 123456)
> grepl( '^([0-9])([0-9])([0-9])\\3\\2\\1$', tmp )
[1] TRUE TRUE FALSE
>
you could convert the numbers to character, split into individual characters (strsplit), reverse each number (sapply and rev), then paste the values back together (paste) and covert back to numbers (as.numeric). But I think the above is better if you are just interested in 6 digit palendromes.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With