Hi few comments r-help-boun...@r-project.org napsal dne 01.02.2010 14:51:17:
> > 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) is same as num1 <- 1:n > for(i in 1:n)num1[i]=pc[1]%*%X[i,1] If I understand what the above code does I am a bit surprised pc[1] is > pc[1] [1] 0.525037 for each number in cycle X[i,1] is again a number > X[1,1] [1] 0.7512862 > X[2,1] [1] 0.5020333 > so it basically results in pc[1] * X[,1] which you can compute for all 4 columns by kronecker(pc, X, "*") But I wonder if this is what you really want. Maybe you shall think it over again and try with some smaller manageable subset lit smallX <- X[1:5,] do all your computation and if it does not produce what you want, specify what you want. Regards Petr > 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. > > ______________________________________________ > R-help@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.