Reverse digits in R

亡梦爱人 提交于 2019-12-03 03:30:19

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.

I don't think rev quite does it. It reverses the elements of the vector, while the question is how to reverse the elements in the vector.

> nums <- sapply(1:10,function(i)as.numeric(paste(sample(1:9,6,TRUE),collapse="")))
> nums
 [1] 912516 568934 693275 835117 155656 378192 343266 685182 298574 666354
> sapply(strsplit(as.character(nums),""), function(i) paste(rev(i),collapse=""))
 [1] "615219" "439865" "572396" "711538" "656551" "291873" "662343" "281586" "475892" "453666"
Shane

Edit: I misread the question. Here's my answer for posterity.


You can use the rev function:

> 1:10
 [1]  1  2  3  4  5  6  7  8  9 10
> rev(1:10)
 [1] 10  9  8  7  6  5  4  3  2  1

If you are interested in the reversals for their own sake, you can use sub with a longer version of Greg's regexp:

> x
[1] 123321 343324 563660
> sub( '^([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])','\\6\\5\\4\\3\\2\\1', x)
[1] "123321" "423343" "066365"

Although is this quicker than split/rev/paste?

This should work in the general case, with any choice of base:

is.palindromic <- function(x, base=10)
{
    p <- 0
    m <- floor(log(x,base))
    sig <- -1
    for (i in m:0)
        {
        tp <- floor(x/base^i)
        a <- i+1
        b <- m+1-i
        if(a==b){c<-0}else{c<-a*b;sig<-sig*-1}
        p <- p + tp*c*sig
        x <- x - tp*base^i
        }
    return(!as.logical(p))
}

There is function in stringi package for that - stri_reverse

require(stringi)
stri_reverse("123456")
## [1] "654321"

Now palindrome function might as simple as that:

palindrome <- function(x) stri_reverse(x)==x
palindrome(c("651156","1234321"))
## [1] TRUE  TRUE
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!