Search code examples
rfunctionoutputloess

R function no output loess span


So I have written a function,that should find me the span for the loess function that corresponds to the degrees of freedom for an equation:

m <- function(x) x+4*cos(7*x)
x<-seq(-1,1,length=101)

to find the degrees of freedom I used the identity matrix

y<-diag(101)
slp<-matrix(0,nrow=101,ncol=101)
snw<- is the hat matrix

here my function, I want it to output the span for which is approximately equal to the same degrees of freedom in hat matrix snw (sum of it diagonals)

y<-diag(101)
dflp<-function(span,value)
       {
        for(q in 1:301)
          {          
          for(i in 1:101)
            {
            slp[,i]<-predict(loess(y[,i]~x,span=span[q]),newdata=x)
            }
          if(sum(diag(slp))-value==0)
            {
             cat("span:",format(span[q]),"\n")
             break
            }
          }
        }

It doesn't seem to output anything, and the value of q is always 7.

Thank you.

NOTE: This is not homework.


Solution

  • There does not appear to be anything wrong with your logic. You are performing a grid search on a number of candidate span. You stop searching when the resulting degree of freedom matches the one given by snw.

    You get no returned value from your function dflp, because you lack a return(span[q]) at the end of your function.

    Another suggestion I would give, is similar to a comment above. "Convergence" is never judged by exact 0, but up to some tolerance. Normally we use relative tolerance:

    abs(diag(slp)-value) / value < 1e-6  ## tol = 1e-6