2015-02-11 43 views
5

我需要将数字向量转换为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 
    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 

是否有其他方法可以将数值转换为R中的字符?感谢您的任何建议。

+1

你或许可以找到一对夫妇更多的方法来做到这一点在最近这次[主题](http://stackoverflow.com/questions/28412049 /布尔之间的差异 - 作为整数和零布尔值)在哪里我问到关于将布尔变成整数。 – LauriK 2015-02-11 07:25:06

回答

5

既然你已经四舍五入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中真正相关?)

+0

感谢您的提示。独特是一个很好的建议,因为我的真实数据有任何重复的值。 – Bangyou 2015-02-12 00:02:21

7

其实好像formatC变快:

library(microbenchmark) 
a <- round(runif(100000), 2) 
microbenchmark(
    as.character(a), 
    formatC(a), 
    format(a), 
    sprintf('%.2f', a), 
    gettextf('%.2f', a), 
    paste0('', a) 
) 

输出:

Unit: milliseconds 
       expr  min  lq  mean median  uq  max neval 
    as.character(a) 69.58868 70.74803 71.98464 71.41442 72.92168 82.21936 100 
      formatC(a) 33.35502 36.29623 38.83611 37.60454 39.27079 72.92176 100 
      format(a) 55.98344 56.78744 58.00442 57.64804 58.83614 66.15601 100 
    sprintf("%.2f", a) 46.54285 47.40126 48.53067 48.10791 49.12717 65.26819 100 
gettextf("%.2f", a) 46.74888 47.81214 49.23166 48.60025 49.16692 84.90208 100 
     paste0("", a) 86.62459 88.67753 90.80720 89.86829 91.33774 125.51421 100 

sessionInfo

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  
4

其他三个方法我能想到的,其中没有是一样快的gettextf

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

最后一个基本上是as.character.default,绕过了方法调度。所有这些时序大致相同paste(a)

+0

谢谢。我正试图找到将数字向量转换为字符向量的最快方法。 – Bangyou 2015-02-11 05:35:58

+2

好的。我敢肯定,你已经显示了他们:)你的问题是否有其他方式将数字转换为字符 – 2015-02-11 05:37:25

相关问题