Error from defined function

I found this function from here:
http://r-statistics.co/Loess-Regression-With-R.html

data(economics, package="ggplot2")  # load data
economics$index <- 1:nrow(economics)  # create index variable
economics <- economics[1:80, ]  # retail 80rows for better graphical understanding
loessMod10 <- loess(uempmed ~ index, data=economics, span=0.10) # 10% smoothing span
loessMod25 <- loess(uempmed ~ index, data=economics, span=0.25) # 25% smoothing span
loessMod50 <- loess(uempmed ~ index, data=economics, span=0.50) # 50% smoothing span
smoothed10 <- predict(loessMod10) 
smoothed25 <- predict(loessMod25) 
smoothed50 <- predict(loessMod50) 
# Plot it
plot(economics$uempmed, x=economics$date, type="l", main="Loess Smoothing and Prediction", xlab="Date", ylab="Unemployment (Median)")
lines(smoothed10, x=economics$date, col="red")
lines(smoothed25, x=economics$date, col="green")
lines(smoothed50, x=economics$date, col="blue")

Erorr message from following function:
The function is going to detect optimal span for loess regression, I tried to run, but got error message, can anyone fix the issue? Thank you!

calcSSE <- function(x){
loessMod <- try(loess(uempmed ~ index, data=economics, span=x), silent=T)
res <- try(loessMod$residuals, silent=T)
if(class(res)!="try-error"){
if((sum(res, na.rm=T) > 0)){
sse <- sum(res^2)
}
}else{
sse <- 99999
}
return(sse)
}

optim(par=c(0.5), calcSSE, method="SANN")

What error message?

Why don't you make silent = F while you are debugging?

Do you need sse <- sum(res^2, na.rm = TRUE) ?

Also I think you need if(abs(sum(res, na.rm=T)) > 0){

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

You got a curly bracket in the wrong place. Do you expect all res to have a value? If not, you need to penalise any NA values, otherwise you will be treating them as res = 0, which is not what you want. Try this maybe.

calcSSE <- function(x) {
  loessMod <- try(loess(uempmed ~ index, data = economics, span = x), silent = T)
  res <- try(loessMod$residuals, silent = T)
  if (class(res) != "try-error") {
    res[is.na(res)] <- 999
    sse <- sum(res^2)
  } else {
    sse <- 999 ^ 2 * nrow(data)
  }
  return(sse)
}
1 Like

here is the error message:
Error in fn(par, ...) : object 'sse' not found

Thank you.

Thank you! It works!

1 Like