2014-02-24 45 views

回答

2

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 
+0

以供參考,這是na.locf.xts的實驗版本的鏈接https://r-forge.r-project.org/scm/viewvc.php/pkg/xts/R/na.R?view=標記&修訂= 793&根= XTS – RockScience

1
timeIndex <- index(x) 
x <- apply(x, 2, na.locf) 
x <- as.xts(x, order.by = timeIndex) 

這避免了柱逐列數據複製。如果沒有這個,在填充第n列時,將製作1:(n-1)列的副本,並將第n列添加到列中,當n很大時,這會變得過於緩慢。