[R] Iterative loop using "repeat"

Jim Lemon jim at bitwrit.com.au
Sun Jan 6 00:49:53 CET 2013


On 01/05/2013 10:32 PM, mary wrote:
> Thanks for the help:your reply has focused my problem
>
> in particular I'm trying to do a converge process;
>
> the robustm() function is:
> function (x,z)
> 1#  {eigen<-eigen(x)
> 2# d<-madmatrix(z)
> ##I have created this function to calculate "mad" of a whole matrix
> 3# eigenc<-eigen$vectors
> 4# q<-d%*%eigenc
> 5# invQ<-matrix.inverse(q)
> 6# sZ<-mdefpos(z,invQ)                                     ##this function
> serves me to define positive my new matrix Z, it's  X%*%invQ
> 7# madZ<-madmatrix(sZ)
> 8# S_X<-q%*%(madsZ)^2%*%t(q)
> return(S_X)
> }
>
>   reviewing this function I realized that it can not be applied in an
> iterative manner in the next step because every time a new matrix z should
> be fed back into the process and then calculate a new scatter matrix; in the
> code above :
> (x) is a scatter matrix, Z is a matrix (n*p) of original data that I have
> used to obtain a scatter matrix...
> in line 6# I need this new matrix sZ because it will be my new (z) if I
> reiterate the process on the new scatter matrix S_X, in fact my function
> robustm() ask me the scatter matrix and the data matrix so...
> how I can do this...and the reiterate the process so that the matrix
> converges??
>
Hi mary,
There are a few different ways to iterate this. One is recursion, where 
the function calls itself until the desired precision is obtained:

robustm<-function(x,z) {
  # not a good idea to use the function name for the return value
  eigenx<-eigen(x)
  d<-madmatrix(z)
  eigenc<-eigen$vectors
  q<-d%*%eigenc
  invQ<-matrix.inverse(q)
  sZ<-mdefpos(x,invQ)
  madZ<-madmatrix(sZ)
  S_X<-q%*%(madsZ)^2%*%t(q)
  # insert your test for the difference of matrix elements here
  keep_going<-???
  # if the test does not succeed (no difference <= 0.001)
  if(keep_going) xz<-robustm(S_X,sZ)
  else xz<-list(finalx<-S_X,finalz<-sZ)
  return(xz)
}

Jim




More information about the R-help mailing list