R: Make this loop faster using sapply -
i'm new in r , i'm trying figure out how make function faster using sapply, help?
x <- c(0.0, 1.0, 2.0, 3.0, 4.0, 5.7) y <- c(10.0, 7.0, 5.5, 4.5, 3.2, na) z <- c(as.data.frame(cbind(x,y)) vcub=function(y, x, z) { vol<-vector() for(i in 1:dim(z)[1]){ if(is.na(y[i])) { vol[i]<-(((pi*y[i-1]^2)/40000)/3)*(x[i]-x[i-1]) }else{ vol[i]<-(((pi*y[i-1]^2) + (pi*y[i]^2))/80000)*(x[i]-x[i-1]) } } return(as.data.frame(vol)) }
you can vectorize code replacing if
, else
statements in loop ifelse
statement , using vectorized arithmetic in r:
data.frame(vol=ifelse(is.na(y), pi*c(na, head(y, -1)^2)/120000*c(na, diff(x)), pi*(y^2 + c(na, head(y, -1)^2))/80000*c(na, diff(x)))) # vol # 1 na # 2 0.0058512163 # 3 0.0031121402 # 4 0.0019831304 # 5 0.0011973395 # 6 0.0004557404
in general, it's easy vectorize computation when can compute i^th index of result without using of previous indices computed. since formula vol[i]
didn't depend on of previous vol
values, can use basic arithmetic operators.
Comments
Post a Comment