2013-04-26 623 views
1

当我将lm与循环一起使用时遇到问题。我想用xxyy的每四个值来拟合回归线。lm.fit(x,y,offset = offset,singular.ok = singular.ok,...):0(non-NA)的情况下的错误

这里是我的代码,

>xx<-c(0 , 55, 146, 457, 643, 825,1008) 
>yy<-c(NA, 110, 132, 108, 124, 115, 134) 
>n<-length(xx) 
>slop<-rep(NA,n) 
>for (i in 4:n){ 
    x<-xx[i-3:i] 
    y<-yy[i-3:i] 
    slop[i]<-lm(y~x)$coefficients[2] 
    } 
Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) : 
    0 (non-NA) cases 

谁能告诉我,为什么出现这种情况?我尝试手动执行,选取xxyy的每四个值并使用lm,然后R成功运行。

+0

我终于找到了错误,也许这对有同样困惑的人有帮助。在循环中需要t <-i-3,否则当我取大于6的值时,R变得混乱并停止计算。 – fiona 2013-04-26 09:41:47

回答

1

[i-3:i]更改为[(i-3):i]消除了该错误消息。

1

的原因是因为运营商prioriy它不是做(间-:)你所期望的:

对于你的第一次迭代:

4-3:4 
[1] 1 0 
xx[4-3:4] 
[1] 0 
yy[4-3:4] 
[1] NA 

,因此:

lm(yy[1]~xx[1]) 
Error in lm.fit(x, y, offset = offset, singular.ok = singular.ok, ...) : 
    0 (non-NA) cases 

为确保您得到您想要的东西,您需要添加括号以明确说明所需操作员的顺序:

(4-3):4 
[1] 1 2 3 4 

for (i in 4:n){ 
x<-xx[(i-3):i] 
y<-yy[(i-3):i] 
slop[i]<-lm(y~x)$coefficients[2] 
    } 

slop 
[1]   NA   NA   NA -0.023502847 0.001080591 
[6] -0.018919254 0.037666732