我喜欢在数据集上运行method =“loess”,如果发生错误,我想尝试lm方法。以下是我执行此操作的代码,但是仍然失败,有什么想法吗?

df

Date  Duration  Athlete
1/1/2012  60    A
1/2/2012  30    A
1/3/2012  10    B
1/1/2012  5     C
1/2/2012  5     C
1/4/2012  4     C

ggplot(df, aes(Date, Duration, group=Athlete)) + geom_point(position="jitter", size=0.5) +theme_solarized(light = FALSE) +  geom_smooth(method=ifelse(class(try(loess(Duration~Date, df)))=="try-error", "lm","loess"), se=T)

我收到此错误:
Error in simpleLoess(y, x, w, span, degree, parametric, drop.square, normalize,  :
  NA/NaN/Inf in foreign function call (arg 2)
In addition: Warning message:
In simpleLoess(y, x, w, span, degree, parametric, drop.square, normalize,  :
  NAs introduced by coercion
Error in function (el, elname)  :

最佳答案

我认为最好知道将哪种平滑方法传递给ggplot2统计引擎。

例如:

mym <- "loess"
tryCatch(loess(Duration~Date, dat),
         error = function(e) mym <<- "lm")

然后
ggplot(dat, aes(Date, Duration, group=Athlete)) +
  geom_point(position="jitter", size=0.5) +
  geom_smooth(method=mym, se=T)

关于r - 类尝试在ggplot中返回错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13882739/

10-12 17:37