在R中将数字转换为字符的最快方法

在R中将数字转换为字符的最快方法,r,R,我需要将数字向量转换为R中的字符。正如我所知,有不同的方法(见下文) 似乎最快的方法是sprintf和gettextf set.seed(1) a <- round(runif(100000), 2) system.time(b1 <- as.character(a)) user system elapsed 0.108 0.000 0.105 system.time(b2 <- formatC(a)) user system elapsed

我需要将数字向量转换为R中的字符。正如我所知,有不同的方法(见下文)

似乎最快的方法是sprintf和gettextf

set.seed(1)
a <- round(runif(100000), 2)
system.time(b1 <- as.character(a))
   user  system elapsed 
  0.108   0.000   0.105 
system.time(b2 <- formatC(a))
   user  system elapsed 
  0.052   0.000   0.052 
system.time(b3 <- sprintf('%.2f', a))
   user  system elapsed 
  0.044   0.000   0.046 
system.time(b4 <- gettextf('%.2f', a))
   user  system elapsed 
  0.048   0.000   0.046 
system.time(b5 <- paste0('', a))
   user  system elapsed 
  0.124   0.000   0.129 
set.seed(1)

a实际上似乎
formatC
的输出速度更快:

library(microbenchmark)
a <- round(runif(100000), 2)
microbenchmark(
  as.character(a), 
  formatC(a), 
  format(a), 
  sprintf('%.2f', a), 
  gettextf('%.2f', a), 
  paste0('', a)
)
我的
会话信息

R version 3.1.0 (2014-04-10)
Platform: x86_64-apple-darwin13.1.0 (64-bit)

locale:
[1] en_AU.UTF-8/en_AU.UTF-8/en_AU.UTF-8/C/en_AU.UTF-8/en_AU.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] microbenchmark_1.4-2

loaded via a namespace (and not attached):
 [1] colorspace_1.2-4 digest_0.6.4     ggplot2_1.0.0    grid_3.1.0       gtable_0.1.2     MASS_7.3-35     
 [7] munsell_0.4.2    plyr_1.8.1       proto_0.3-10     Rcpp_0.11.3      reshape2_1.4     scales_0.2.4    
[13] stringr_0.6.2    tools_3.1.0    

我能想到的其他三种方法,没有一种比
gettextf
更快

storage.mode(a) <- "character"
mode(a) <- "character"
as.vector(a, "character")

storage.mode(a)既然您已将
a四舍五入到有限精度,请将唯一值转换一次,然后查找这些值

f0 = formatC
f1 = function(x) { ux = unique(x); formatC(ux)[match(x, ux)] }
这给出了相同的结果

> identical(f0(a), f1(a))
[1] TRUE
并且至少对于样本数据集来说更快

> microbenchmark(f0(a), f1(a))
Unit: milliseconds
  expr      min       lq     mean   median       uq      max neval
 f0(a) 46.05171 46.89991 47.33683 47.42225 47.58196 52.43244   100
 f1(a) 10.97090 11.39974 11.48993 11.52598 11.58505 11.90506   100

(尽管这种效率真的与R有关吗?

谢谢。我想找到最快的方法把数字向量转换成字符向量。我很确定你已经展示了:)你的问题是,是否还有其他方法可以将数字转换为字符。你可能会在最近的一篇文章中找到更多的方法来实现这一点,我问了如何将布尔值转换为整数。谢谢你的提示。Unique是一个很好的建议,因为我的真实数据有任何重复的值。
> microbenchmark(f0(a), f1(a))
Unit: milliseconds
  expr      min       lq     mean   median       uq      max neval
 f0(a) 46.05171 46.89991 47.33683 47.42225 47.58196 52.43244   100
 f1(a) 10.97090 11.39974 11.48993 11.52598 11.58505 11.90506   100