如何使用 SSASympOff 为 nls 渐近线函数获取 geom_smooth

how to get a geom_smooth for an nls assymptote function using SSasympOff

我有以下数据框:

df1<- structure(list(Site = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("ALT01"), class = "factor"), Nets = 1:18, Cumulative.spp = c(12L,13L, 15L, 17L, 17L, 17L, 17L, 19L, 19L, 19L, 19L, 20L, 22L, 22L, 22L, 22L, 22L, 22L)), .Names = c("Site", "Nets", "Cumulative.spp"), row.names = c(NA, 18L), class = "data.frame")

我正在尝试使用此函数的 geom_smooth 响应获取 ggplot2 图:

Model1<-nls(Cumulative.spp ~ SSasympOff(Nets, A, lrc, c0), data = df1)

通常如果我有这样的模型:

Model2 <- lm(Cumulative.spp ~ I(log(Nets), data = df1)

我试了两种方法

方法一

我会这样做:

 library(ggplot2)

 ggplot(df1, aes(x=Nets, y = Cumulative.spp)) + geom_point() + geom_smooth(method="lm", formula=y~log(x), fill="blue", fullrange=T) 

但是当我尝试用渐近线做同样的事情时它不起作用:

ggplot(df1, aes(x=Nets, y = Cumulative.spp)) + geom_point() + geom_smooth(method="nls", formula=y~SSasympOff(x, A, lrc, c0), color="blue", fullrange=T) 

但我得到了这个错误和这个情节:

Warning message:
Computation failed in `stat_smooth()`:
$ operator is invalid for atomic vectors 

方法2

我尝试对原始数据帧进行预测以获得置信区间,并对预测值使用 geom_line,对区间使用 geom_ribbon,但是当我这样做时

predict(Model1, df1, interval = "confidence")

但我没有得到置信区间,只有预测值

任何帮助将不胜感激

我想,既然我建议了一个 bootstrap 方法,我可能会演示。在这种情况下,我们将增强残差 (see Wikipedia for more information)。我不太熟悉使用 nls,所以有人可能会提出(有效的)理论上的反对意见。

B <- 2500 # bootstrap iterations, big number
pred_mat <- matrix(0, nrow = 18, ncol = B) # initialize matrix
# extract residuals and predictions from original model
resids <- residuals(Model1)
preds <- predict(Model1)
df1$Pred <- preds
for(i in 1:B){
    # bootstrapped dependent variable
    new_y <- preds + sample(resids, replace = TRUE)
    df1$NewY <- new_y
    # fit model
    Model_Boot <- nls(NewY ~ SSasympOff(Nets, A, lrc, c0), data = df1)
    # extract predictions
    pred_mat[,i] <- predict(Model_Boot)
}

# add 2.5% and 97.5% percentile intervals to df1
df1 <- cbind(df1, t(apply(pred_mat, 1, FUN = function(x) quantile(x, c(.025, .975)))))
# rename appropriately
names(df1)[6:7] <- c('lower','upper')

# make plot
ggplot(df1, aes(x = Nets))+
    geom_point(aes(y = Cumulative.spp))+
    geom_line(aes(y = Pred))+
    geom_ribbon(aes(ymin = lower, ymax = upper),
                alpha = .2, fill = 'blue')

我找到了这种方法,我认为它比 bouncyballs 简单一点,但我会让大家判断更好的答案,尽管我会支持 bouncyball 的答案。

发现这个old post about it, but I couldn't find the as.lm function in nls2, the I found this link有函数,我决定用as.lm.nls函数

ggplot(df1, aes(x=Nets, y = Cumulative.spp)) + geom_point() + geom_line(y = predict(as.lm.nls(Model1), interval = "confidence")[,1]) + geom_ribbon(ymax = predict(as.lm.nls(Model1), interval = "confidence")[,3], ymin = predict(as.lm.nls(Model1), interval = "confidence")[,2], fill = "blue", alpha = 0.5)

我得到这个结果的速度比使用 bootstrap 方法更快