2017-04-03 86 views
-1

我有一个关于如何在回归之后将NA值包含在向量中的问题。在线性模型R中包含NA

这里是我的代码:

m <- c(100, 108, 105, 120) 
n <- c(5, NA, 10, 8) 

b <- lm(n~m)$fitted.values 

# This returns: 

     1  3  4 
6.961538 7.384615 8.653846 

我需要列2被包括在内,无论是与零或NA,所以它由而不是3 4列对如何做到这一点的任何建议?

+0

需要再次致电预测。 '预测(lm(n〜m),数据帧(m = c(100,108,105,120)))' – OganM

回答

1

为了您的提取拟合值也将包括NA(即4列),可以使用na.excludelm()

na.exclude确实casewise缺失相对于预测和准则,在这种情况下,功能fitted()将填补输出与NA

所以,你的代码看起来像这样

m <- c(100, 108, 105, 120) 
n <- c(5, NA, 10, 8) 

# ordinary linear model 
b <- lm(n~m, na.action = na.exclude) 

# extract elements from a linear model fit 
fitted(b) 

# And output of NA column 
fitted(b) 
     1  2  3  4 
6.961538  NA 7.384615 8.653846