遍历统计模型并绘制拟合的响应曲线

时间:2018-12-10 14:44:35

标签: r plot lapply coefficients

我在列表中有一系列统计模型,我想画出它们的系数。在此模型列表中,我有各种响应和解释变量,以及各种统计函数(例如指数函数和线性函数)。

DF<- as.data.frame(matrix(sample(1:50, 1*2000, replace=TRUE), ncol=4))
colnames(DF) <- c("Response_1","Response_2","Explanatory_1","Explanatory_2")
DF$Factor <- rep(c("Control","Impact"), each = 250)

List_models <- list(lm(Response_1~exp(Explanatory_1):Factor, data=DF), 
                lm(Response_1~Explanatory_2:Factor, data=DF),
                lm(Response_2~Explanatory_1:Factor, data=DF),
                lm(Response_2~exp(Explanatory_2):Factor, data=DF))

我猜测某种形式的lapply函数在这里可以工作,但是我不知道如何在更改与x相关联的函数或更改绘制的Response和Explanatory变量时执行此操作。下面的代码产生了理想的结果,但是我想用某种循环函数来创建它。

par(mfrow=c(2,2))
plot(Response_1~Explanatory_1,data=DF,type="n")
curve(List_models[[1]]$coefficients[1]+List_models[[1]]$coefficients[2]*exp(x), add = TRUE)
plot(Response_1~Explanatory_2,data=DF,type="n")
curve(List_models[[2]]$coefficients[1]+List_models[[2]]$coefficients[2]*x, add = TRUE)
plot(Response_2~Explanatory_1,data=DF,type="n")
curve(List_models[[3]]$coefficients[1]+List_models[[3]]$coefficients[2]*x, add = TRUE)
plot(Response_2~Explanatory_2,data=DF,type="n")
curve(List_models[[4]]$coefficients[1]+List_models[[4]]$coefficients[2]*exp(x), add = TRUE)

在此先感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

正如Gregor所说,您只需要predict来获得预测值。为简化起见,我敦促您使用ggplot:

DF$model1 <- predict(List_models[[1]])
DF$model2 <- predict(List_models[[2]])

library(ggplot2)
ggplot(DF)+
  geom_point(aes(X,Y,color = "initial values"))+
  geom_line(aes(X,model1,color = "model1"))+
  geom_line(aes(X,model2,color = "model2"))+
  facet_wrap(~Factor)

enter image description here

如果您有很多模型,并且想循环播放,则需要这样的东西:

for(i in 1:length(List_models))
    {DF[[paste0("model",i)]] <-  predict(List_models[[i]])}
library(data.table)
DF <- setDT(DF)

library(ggplot2)
ggplot(melt(DF,measure.vars = patterns("model")))+
  geom_point(aes(X,Y,color = "initial values"))+
  geom_line(aes(X,value,color = variable))+
  facet_wrap(~Factor)