Speed up a loop in R -
i using following function estimate kernel density of data
kdens = function(x,h,n) { fx = matrix(0,n,1) kx = ak(x,h,n) (i in 1:n) { fx[i] = sum(kx[i,], na.rm=t)/n } return(fx) } i know not first question speeding loop. checked around in site, found using apply function faster, not case if manage correctly set loop.
in above code, every "not needed thing" left out of loop, - if understood correctly - suggested speed computation. however, made comparison between above kdens function , density function implemented in r default. well, density needs 1 or 2 seconds, while kdens needs ~30 on machine.
trywiththis <- rnorm(4800) x = trywiththis n = length(trywiththis) h = 1.059*sd(trywiththis , na.rm=t)*(n^(-0.2)) edit: information provided not complete
kerf = function(x){ return(dnorm(x)) } ker = function(x,x0,h){ temp = kerf((x-x0)/h)/h return(temp) } ak = function(x,h,n) { k = array(0,c(n,n)) (i in 1:n) { (j in 1:n) { k[i,j] = ker(x[i],x[j],h) }} return(k) } suppose want speed kdens function, how ?
try this... original 4800 length dataset takes 2.5 seconds.
kdens2 = function(x,h,n) { kx <- outer( x , x , fun = function(x,y) dnorm( ( x-y ) / h ) / h ) fx <- as.matrix( rowsums( kx ) / n , ncol = 1 ) return( fx ) } testing
set.seed(1) trywiththis <- rnorm(480) x = trywiththis n = length(trywiththis) h = 1.059*sd(trywiththis , na.rm=t)*(n^(-0.2)) #produce same result? (posibly not identical because of 'dnorm' function) all.equal( kdens(x,h,n) , kdens2(x,h,n) ) [1] true #rough timing on n=480 length data... system.time( kdens2(x,h,n) ) # user system elapsed # 0.01 0.00 0.02 system.time( kdens(x,h,n) ) # user system elapsed # 2.7 0.0 2.7 and when n=4800...
system.time( kdens2(x,h,n) ) user system elapsed 2.33 0.19 2.51
Comments
Post a Comment