[英]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? 我是R语言的新手,我想弄清楚如何使用sapply来提高我的功能,有帮助吗?
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: 您可以通过将if
循环中的if
和else
语句替换为ifelse
语句,并在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. 通常,当您可以在不使用任何先前计算的索引的情况下计算结果的第i个索引时,很容易对计算进行向量化。 Since your formula for vol[i]
didn't depend on any of the previous vol
values, you can just use basic arithmetic operators. 由于您的vol[i]
公式不依赖于任何先前的vol
值,因此您可以使用基本算术运算符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.