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
}
}
任何幫助表示讚賞
最好
非常感謝Heroka!你的代碼速度提高了2倍。你認爲我可以用mclappy嗎?我嘗試了以下,它不起作用:x1 < - runif(1000000,5.0,7.5).. t < - mclapply(x1,formatter,mCores = 4) 警告消息: 所有調度的核心遇到錯誤用戶代碼 – user22364
我對mclappy不熟悉。但是,格式化程序(x1)在我的機器上運行了7秒鐘。不知道這是否對你來說太慢(我經常花費更多的時間來優化代碼,而不是獲得授權) – Heroka
再次感謝我使用apply(x1),因爲我的代碼是基於一個值的,但是使用formatter(x1)比我的代碼快13倍,這非常棒! – user22364