2015-09-04 73 views
1

转换的十进制数我想转换小数坐标(例如-62.54879632547)为固定宽度的字符串如下:带负号以固定宽度的字符串

负数 - >前导0

正数 - >前导1

然后3位数字的整数部分

62 - > 062

2 - > 002

然后十进制(和舍去小数)后的6位数字

0.54879632547 - > 548796

最终restuls:

-62.54879632547 - > 0062548796(即0 062 548796)

如何在R中实现快速高效?

我做了以下的功能,但它是相当缓慢的(与lapply超过百万价值的使用时):

 formatCoordinate <- function (x) { 
     if (!is.na(x)) { 
     sign <- ifelse(x < 0, 0, 1) 
     castIntergerPart <- function (x) { 
      #integer part should be exactly 3 digits with leading zeros if necessary 
      if (abs(x) < 10) { 
      intgerPart <- paste0("00", abs(as.integer(x))) 

      }else if (abs(x) >=10 & abs(x) < 100) { 
      intgerPart <- paste0("0", abs(as.integer(x))) 

      }else if (abs(x) >= 100) { 
      intgerPart <- paste0(abs(as.integer(x))) 
      } 
     } 

     castDecimalPart <- function(x) { 
      s <- toString(x) 
      sub(".*?.(.*?);.*", "\\1", s) 
      substr(unlist(strsplit(s, split='.', fixed=TRUE))[2], 1, 6) 
     } 

     formattedCoordinate = paste0(sign, castIntergerPart(x), castDecimalPart(x)) 
     }else{ 
     NA  
     } 
    } 

任何帮助表示赞赏

最好

回答

2

使用一些字符串格式和正则表达式。可以处理数字的向量。

formatter <- function(x){ 
    first_part <- ifelse(x < 0 , "0","1") 
    second_part <- abs(as.integer(x)) 
    third_part <- substr(gsub(".+\\.","",as.character(x)),1,6) 
    result <- ifelse(!is.na(x),sprintf("%s%03d%s",first_part,second_part,third_part), NA) 
    result 

} 
> formatter(-62.54879632547) 
[1] "0062548796" 
+0

非常感谢Heroka!你的代码速度提高了2倍。你认为我可以用mclappy吗?我尝试了以下,它不起作用:x1 < - runif(1000000,5.0,7.5).. t < - mclapply(x1,formatter,mCores = 4) 警告消息: 所有调度的核心遇到错误用户代码 – user22364

+0

我对mclappy不熟悉。但是,格式化程序(x1)在我的机器上运行了7秒钟。不知道这是否对你来说太慢(我经常花费更多的时间来优化代码,而不是获得授权) – Heroka

+0

再次感谢我使用apply(x1),因为我的代码是基于一个值的,但是使用formatter(x1)比我的代码快13倍,这非常棒! – user22364