user1471980
user1471980

Reputation: 10626

use glm method if loess method returning error

df

Date      Ovserv  Team
1/1/2012  10      USA
1/2/2012  30      USA
1/3/2012  28      USA
1/4/2012  79      USA
1/5/2012  24      USA
1/1/2012  45      Japan
1/2/2012  10      Japan
1/3/2012  56      Japan
1/4/2012  60      Japan
1/5/2012  67      Japan

I really like loess and like to use it whenever I can. I am working with variety of different data frames where I am trying to use loess method to graph. However, due to some inconsistencies (some data frames not having enough data points), I am getting this error:

Error in predLoess(object$y, object$x, newx, object$s, object$weights,

Would it be possible to use method="glm" in the event that I would get error using ggplot2 method "loess"?

ggplot(df, (Date, Observ, group=Team, colour=Team)) + 
   geom_smooth(method="loess", se=T, size=1)

Any ideas how I would address this problem?

Upvotes: 1

Views: 467

Answers (1)

Señor O
Señor O

Reputation: 17412

The statement class(try(loess(y~x, df)))=="try-error" will give TRUE if there's not sufficient data for loess.

You can try something along the lines of

ggplot(....) + geom_smooth(method=ifelse(class(try(loess(y~x, df)))=="try-error",
                                          "glm","loess")....) 

And add silent=TRUE to the try arguments if you don't want to see the error messages.

Upvotes: 6

Related Questions