R中的反转数字 [英] Reverse digits in R

查看:213
本文介绍了R中的反转数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在R中反转一串数字?

例如,我有一个约1000个六位数的向量,我想知道它们是否是回文.我想创建第二套正好相反的东西,所以我可以做一场比赛.

解决方案

它实际上是要测试为回文数的数字的十进制表示形式,而不是数字本身(255是十六进制和二进制形式的古生物),但是不是十进制).

您可以使用模式匹配相当简单地完成此操作:

> tmp <- c(100001, 123321, 123456)
> grepl( '^([0-9])([0-9])([0-9])\\3\\2\\1$', tmp )
[1]  TRUE  TRUE FALSE
> 

您可以将数字转换为字符,分割为单个字符(strsplit),反转每个数字(sapply和rev),然后将值粘贴回(粘贴)并隐式恢复为数字(as.numeric).但是我认为,如果您只对6位数古动物感兴趣,那么上面的方法会更好.

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.

解决方案

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.

这篇关于R中的反转数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆