我正在尝试计算线性回归残差和自变量之间的相关系数p
。
基本上,线性回归估计当前销售额为当前价格p
和过去价格的函数p1
。当前价格向量的mydf$p
长度为8,但残差为长度7的向量,因为由于的NA
值而删除了一个条目p1
。
# lag vector and pad with NAs
# Source: http://heuristically.wordpress.com/2012/10/29/lag-function-for-data-frames/
lagpad <- function(x, k) {
if (!is.vector(x))
stop('x must be a vector')
if (!is.numeric(x))
stop('x must be numeric')
if (!is.numeric(k))
stop('k must be numeric')
if (1 != length(k))
stop('k must be a single number')
c(rep(NA, k), x)[1 : length(x)]
}
mydf <- data.frame(p = c(10, 8, 10, 9, 10, 9, 10, 8))
mydf$p1 <- lagpad(mydf$p,1)
mydf$sales <- with(mydf, 200 - 15 * p + 5 * p1) + rnorm(nrow(mydf), 0,0.13)
model <- lm(data = mydf, formula = 'sales ~ p + p1')
print(summary(model))
print(cor(residuals(model), mydf$p))
# Error in cor(residuals(model), mydf$p) : incompatible dimensions
在这种特殊情况下,很容易使用mydf$p[2:8]
代替mydf$p
。但是,通常,随机位置可能会有多行,然后删除NA。删除包含NA的行后,如何访问回归中实际使用的自变量?
您可以从model$model
,然后从p
列中获取用于拟合模型的实际数据:
cor(residuals(model), model$model$p)
或者,is.na(mydf$p1)
将告诉您其中的哪些行mydf
具有NA
in列p1
:
cor(residuals(model), mydf$p[!is.na(mydf$p1)])
通常,is.na(x)
告诉我们中的元素是否x
为NA
:
> is.na(c(1,2,NA,4,NA,6))
[1] FALSE FALSE TRUE FALSE TRUE FALSE
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句