[R] avoiding loops in equation
Julius Tesoro
jutesoro at yahoo.com
Sat Oct 17 04:51:58 CEST 2009
To illustrate my problem, I have a complex code of several matrices and a vector. To simplify I only used two matrices and a vector as an example:
pex<-function(acc, pga, std){
(acc-pga)/std
}
acc<-seq(.1,1,.1)
pga<-matrix(rnorm(9,4,.1),3,3)
std<-matrix(rnorm(9,4,.5),3,3)
I tried calculating the above function for each element of acc using:
for (x in 1:length(acc)){
a1<-pex(acc[x],pga,std)
if(x==1){a2<-a1
}else {a2<-rbind(a2,a1)
}
I want to recode the following using sapply
a2<-sapply(acc, function(x) pex(x,pga,std))
but what I get is a different result.
Anyone knows how to rewrite the above function without using loops?
Thanks everyone.
More information about the R-help
mailing list