2013-01-12 175 views
-5

我有一个函数行有问题。函数行()不起作用

这是我至今写:

model.ew<-lm(Empl~Wage) 

summary(model.ew) 

plot(Empl,Wage) 

mean<-1:500 

lw<-1:500 

up<-1:500 

for(i in 1:500){ 

    mean[i]<-predict(model.ew,data.frame(Wage=i*100),interval="confidence",level=0.90)[1] 

    lw[i]<-predict(model.ew,data.frame(Wage=i*100),interval="confidence",level=0.90)[2] 

    up[i]<-predict(model.ew,data.frame(Wage=i*100),interval="confidence",level=0.90)[3] 

} 

plot(Wage,Empl) 

lines(mean,type="l",col="red") 

lines(up,type="l",col="blue") 

lines(lw,type="l",col="blue") 

我的问题I S出现在我的阴谋没有行,我想不通为什么。

有人可以帮我吗?

+1

从哪来的'Empl'和'工资'?请包含示例数据。 –

+1

'predict.lm'是矢量化的。不需要for循环。研究'?predict.lm'中的例子。 – Roland

+0

此外,你想传递x和y值到'行',而不仅仅是x。 – Roland

回答

1

你真的需要阅读R.转到一些介绍手册,该页面,然后选择一个说明使用的R用线性回归:http://cran.r-project.org/other-docs.html

首先,我们需要做一些数据:

set.seed(42) 
Wage <- rnorm(100, 50) 
Empl <- Wage + rnorm(100, 0) 

现在我们运行你的回归,并绘制线:

model.ew <- lm(Empl~Wage) 
summary(model.ew) 
plot(Empl~Wage) # Note. You had the axes flipped here 

你的第一个问题是,你翻转轴。因变量(Empl)在垂直轴上。这是你没有在剧情上得到任何线条的主要原因。要获得预测线需要在所有没有循环,也只使用单一的情节呼叫matlines():

xval <- seq(min(Wage), max(Wage), length.out=101) 
conf <- predict(model.ew, data.frame(Wage=xval), 
    interval="confidence", level=.90) 
matlines(xval, conf, col=c("red", "blue", "blue")) 

这一切就是这么简单。 enter image description here