简体   繁体   中英

R: Make this loop faster using sapply

I'm very new in R and i'm trying to figure it out how to make my function faster using sapply, any 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 this code by replacing your if and else statements in the for loop with an ifelse statement and 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 to vectorize a computation when you can compute the i^th index of your result without using any of the previous indices you computed. Since your formula for vol[i] didn't depend on any of the previous vol values, you can just use basic arithmetic operators.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM