R函數替代na.locf.xts(具有多列XTS使用時非常慢)
XTS ::: na.locf.xts
極慢一列多列的多列xxt。 在na.locf.xts代碼中的列確實存在一個循環
我試圖找到避免此循環的方法。
有什麼想法?
R函數替代na.locf.xts(具有多列XTS使用時非常慢)
XTS ::: na.locf.xts
極慢一列多列的多列xxt。 在na.locf.xts代碼中的列確實存在一個循環
我試圖找到避免此循環的方法。
有什麼想法?
na.locf.xts
中的循環比較慢,因爲它會爲對象中的每個列創建整個對象的副本。循環本身並不慢;由[.xts
創建的副本很慢。
R-Forge上有一個na.locf.xts
版本的實驗版本,因此將列上的循環移動到C,避免了複製對象。對於非常大的物體,速度要快很多。
set.seed(21)
m <- replicate(20, rnorm(1e6))
is.na(m) <- sample(length(x), 1e5)
x <- xts(m, Sys.time()-1e6:1)
y <- x[1:1e5,1:3]
> # smaller objects
> system.time(a <- na.locf(y))
user system elapsed
0.008 0.000 0.008
> system.time(b <- xts:::.na.locf.xts(y))
user system elapsed
0.000 0.000 0.003
> identical(a,b)
[1] TRUE
> # larger objects
> system.time(a <- na.locf(x))
user system elapsed
1.620 1.420 3.064
> system.time(b <- xts:::.na.locf.xts(x))
user system elapsed
0.124 0.092 0.220
> identical(a,b)
[1] TRUE
以供參考,這是na.locf.xts的實驗版本的鏈接https://r-forge.r-project.org/scm/viewvc.php/pkg/xts/R/na.R?view=標記&修訂= 793&根= XTS – RockScience
timeIndex <- index(x)
x <- apply(x, 2, na.locf)
x <- as.xts(x, order.by = timeIndex)
這避免了柱逐列數據複製。如果沒有這個,在填充第n列時,將製作1:(n-1)列的副本,並將第n列添加到列中,當n很大時,這會變得過於緩慢。
爲什麼不會有循環?你是(錯誤地)認爲循環太慢的人之一嗎? –