我知道3种方法可以做到这一点,其中一种在其他答案中有描述。以下是其他选项。第一种使用nls()来拟合模型,investr::predFit用于进行预测和CI:
library(tidyverse)
library(investr)
data <- tibble(date = 1:7,
cases = c(0, 0, 1, 4, 7, 8.5, 8.5))
model <- nls(cases ~ SSlogis(log(date), Asym, xmid, scal), data= data )
new.data <- data.frame(date=seq(1, 10, by = 0.1))
interval <- as_tibble(predFit(model, newdata = new.data, interval = "confidence", level= 0.9)) %>%
mutate(date = new.data$date)
p1 <- ggplot(data) + geom_point(aes(x=date, y=cases),size=2, colour="black") + xlab("Date") + ylab("Cases")
p1+
geom_line(data=interval, aes(x = date, y = fit ))+
geom_ribbon(data=interval, aes(x=date, ymin=lwr, ymax=upr), alpha=0.5, inherit.aes=F, fill="blue")+
theme_classic()
![enter image description here](https://istack.dev59.com/RcBJs.webp)
另一个选择是使用“drc” 包进行模型拟合和预测(也称为剂量-反应曲线)。该包使用内置的启动器函数(需要使用或创建),但 “drc” 类对象具有许多有用的方法,其中一个是支持置信区间的 predict.drc 方法(尽管仅适用于某些内置的自启动器)。以下是使用“drc” 包的示例:
library(drc)
model_drc <- drm(cases~date, data = data, fct=LL.4())
predict_drc <- as_tibble(predict(model_drc, newdata = new.data, interval = "confidence", level = 0.9)) %>%
mutate(date = new.data$date)
p1+
geom_line(data=predict_drc, aes(x = date, y = Prediction ))+
geom_ribbon(data=predict_drc, aes(x=date, ymin=Lower, ymax=Upper), alpha=0.5, inherit.aes=F, fill="red")+
ggtitle("with package 'drc'")+
theme_classic()
![enter image description here](https://istack.dev59.com/dN5lS.webp)
关于'drc'包的更多信息:期刊论文,博客文章描述自定义自启动的drc,以及文档。
dput(data)
的输出结果。如果太大,请附上dput(head(data, 20))
的输出结果。 - Rui Barradaspredict.nls
的文档对参数se.fit
说道: "目前该参数被忽略。" - Rui Barradas