[R] How to repeat "for" function?

ayu2008 ayuazwal at yahoo.com
Mon Feb 1 14:51:17 CET 2010


Dear Users,

I have one problem here, I tried many time and even read a few notes on
writing function but still..... 


Can anyone help me on how to simplify Part B (please refer the programming
below), so that I don't have to repeat the calculation of "num" and "r" ? 



Thank you very much..every help is very much appreciated...


## Part A
n=1400
m=matrix(c(0,0,0,0),4,1)
m2=matrix(c(0,2,0,0),4,1)
c4<-matrix(c(1.0,0.2,-0.5,0.3,0.2,1,0.2,-0.5,-0.5,0.2,1,0.2,0.3,-0.5,0.2,1),4,4,byrow=T)
set.seed(428)
X=mvrnorm(n,m2,c4)
X.pca<-princomp(X)
loadings(X.pca)
pc=X.pca$loadings[,1]

##  Part B 
num1=rep(1:n)
for(i in 1:n)num1[i]=pc[1]%*%X[i,1]
num2=rep(1:n)
for(i in 1:n)num2[i]=pc[2]%*%X[i,2]
num3=rep(1:n)
for(i in 1:n)num3[i]=pc[3]%*%X[i,3]
num4=rep(1:n)
for(i in 1:n)num4[i]=pc[4]%*%X[i,4]

den=rep(1:n)
for(i in 1:n)den[i]=pc%*%X[i,]


r1=num1/den
r2=num2/den
r3=num3/den
r4=num4/den
MLAV=sum(r2>r1 & r2>r3 & r2>r4)
MLAV

Best regards,
ayu


-- 
View this message in context: http://n4.nabble.com/How-to-repeat-for-function-tp1458806p1458806.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list