Reverse digits in R

后端 未结 7 2062
清歌不尽
清歌不尽 2020-12-15 11:48

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 wo

7条回答
  •  旧时难觅i
    2020-12-15 12:20

    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.

提交回复
热议问题