循环lm预测用于绘制多条线

时间:2017-06-14 23:07:48

标签: r loops subset lm predict

我想为每个ID绘制线性模型线。

如何使用不同长度的序列为多个lms(或glms)创建预测?我试过了:

#some fake data
res<-runif(60,1,20)
var<-runif(60,10,50)
ID<-rep(c("A","B","B","C","C","C"),10)
data<- data.frame(ID,res,var)

#lm
library(data.table)
dt <- data.table(data,key="ID")
fits <- lapply(unique(data$ID),
function(z)lm(res~var, data=dt[J(z),], y=T))

#sequence for each ID of length var(ID)
mins<-matrix(with(data, tapply(var,ID,min)))
mins1<-mins[,1]
maxs<-matrix(with(data,tapply(var,ID,max)))
maxs1<-maxs[,1]
my_var<-list()
for(i in 1:3){
 my_var[[i]]<- seq(from=mins1[[i]],to=maxs1[[i]],by=1)
}

# predict on sequences
predslist<- list()
predslist[[i]] <- for(i in 1:3){
  dat<-fits[[i]]
  predict(dat,newdata= data.frame("var"= my_var,type= "response", se=TRUE))
}

预测结果错误

2 个答案:

答案 0 :(得分:1)

仅为var [i]范围绘制lm行可在ggplot:

中使用
library(ggplot2)
# create ID, x, y as coded by Matt
p <- qplot(x, y)
p + geom_smooth(aes(group=ID), method="lm", size=1, se=F)

答案 1 :(得分:0)

这就是你想要的东西吗?

# generating some fake data
ID <- rep(letters[1:4],each=10)
x <- rnorm(40,mean=5,sd=10)
y <- as.numeric(as.factor(ID))*x + rnorm(40)

# plotting in base R
plot(x, y, col=as.factor(ID), pch=16)

# calling lm() and adding lines
lmlist <- lapply(sort(unique(ID)), function(i) lm(y[ID==i]~x[ID==i]))
for(i in 1:length(lmlist)) abline(lmlist[[i]], col=i)

不知道绘图部分是否被卡住了,但如果传入从abline()返回的对象,lm()函数将绘制最小二乘线。

如果你想要最小二乘线开始&amp;结束与min&amp; max x values,这是一个解决方法。它不漂亮,但似乎有效。

plot(x, y, col=as.factor(ID), pch=16)
IDnum <- as.numeric(as.factor(ID))
for(i in 1:length(lmlist)) lines(x[IDnum==i], predict(lmlist[[i]]), col=i)