r - 如何反转R中的数字

标签 r

我想编写一个函数来反转任何数字的顺序。这是我所拥有的,但它不起作用。请帮我!

n=123
rev_number=function(n){
 m=strsplit(as.character(n),"")
 if (m==rev(m)) print("reversed number")
}

所需的输出是 n=321

最佳答案

我觉得反转整数应该留在整数世界而不是进入字符串操作世界。在 R 中似乎没有用于此类任务的内置函数,因此我们可以创建一个,例如使用 Rcpp 包。这是一个例子

library(Rcpp)
cppFunction('int Reverse_CPP(int x) {
  int reverse = 0;
  while(x != 0) {
        int remainder = x%10;
        reverse = reverse*10 + remainder;
        x/= 10;
    }
  return reverse ; 
}')

Reverse_CPP(1234)
# [1] 4321

这是一个矢量化版本
cppFunction('IntegerVector Reverse_CPP2(IntegerVector x) {
  int n = x.size();
  IntegerVector out(n);
  IntegerVector xx = clone(x); // Will need this if you don"t want to modify x in place

  for (int i = 0; i < n; ++i){
    int reverse = 0;
    while(xx[i] != 0) {
       int remainder = xx[i]%10;
       reverse = reverse*10 + remainder;
       xx[i]/= 10;
    }
    out[i] = reverse;
   }

   return out;

}')

Reverse_CPP2(c(12345, 21331, 4324234, 4243))
# [1]   54321   13312 4324234    3424

请注意,我必须添加 IntegerVector xx = clone(x);并因此大幅减慢功能(请参阅@alexis_laz 评论),因为 Rcpp 将修改原始 x另有引用。如果您传递的是裸向量,或者您不关心原始向量是否正在被修改,则不需要它

针对其他向量化字符串操作函数的一些基准测试
Stringi <- function(x) as.integer(stringi::stri_reverse(x))

Base <- function(x) {
  as.integer(vapply(lapply(strsplit(as.character(x), "", fixed = TRUE), rev),
                    paste, collapse = "", FUN.VALUE = character(1L)))
}


library(microbenchmark)
set.seed(123)
x <- sample(1e3L:1e7L, 1e5, replace = TRUE)

microbenchmark(
               Base(x),
               Stringi(x),
               Reverse_CPP2(x)
)

# Unit: milliseconds
#            expr        min         lq      mean     median          uq         max neval cld
#         Base(x) 855.985729 913.602215 994.60640 976.836206 1025.482170 1867.448511   100   c
#      Stringi(x)  86.244426  94.882566 105.58049 102.962924  110.334702  179.918461   100  b 
# Reverse_CPP2(x)   1.842699   1.865594   2.06674   1.947703    2.076983    6.546552   100 a  

关于r - 如何反转R中的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35825343/

相关文章:

R将具有多个字符串长度的列表转换为数据帧

r - 将两个二进制变量合并为一个具有四个可能值的变量

r - 在 r 中混淆聚类数据并保护隐私的技术

r - 使用ggarrange时如何避免轴线消失?

r - 如何使用 knitr/Sweave 中的 R 变量值在 LaTeX 中编写 if-then 语句

r - 将R中的两个数据帧逐个元素粘贴在一起

r - 一个 Shiny 的应用程序中的多个reactiveValues

r - R 中对一组不同解释变量的并行面板 logit 计算

r - 在 Shiny 的服务器上增加堆栈维度

python - 在 R 中做 dt[,y :=myfun(x), by=list(a,b,c)] 的 pythonic 方法是什么?