2015-02-11 44 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

相關問題