如何使用相关或协方差矩阵而不是使用R的数据帧来获得回归系数和模型拟合?

时间:2016-07-25 00:43:11

标签: r regression linear-regression lm

我希望能够通过提供相关或协方差矩阵而不是data.frame来从多元线性回归中回归系数。我意识到你失去了一些与确定截距等有关的信息,但是相关矩阵应该足以得到标准化的系数和方差估计。

例如,如果您有以下数据

# get some data
library(MASS)
data("Cars93")
x <- Cars93[,c("EngineSize", "Horsepower", "RPM")]

您可以按如下方式运行回归:

lm(EngineSize ~ Horsepower + RPM, x)

但是,如果不是拥有数据,而是使用相关矩阵或协方差矩阵,那该怎么办呢?

corx <- cor(x)
covx <- cov(x)
  • R中的哪个函数允许您根据相关性或协方差矩阵运行回归?理想情况下,它应该类似于lm,以便您可以轻松获得诸如r平方,调整后的r平方,预测值等内容。据推测,对于其中一些内容,您还需要提供样本大小以及可能的方法向量。但那也没关系。
是的,例如:

lm(EngineSize ~ Horsepower + RPM, cov = covx) # obviously this doesn't work

请注意,Stats.SE上的这个答案提供了为什么可能的理论解释,并提供了一些用于计算系数的自定义R代码的示例?

4 个答案:

答案 0 :(得分:2)

使用lavaan,您可以执行以下操作:

library(MASS)
data("Cars93")
x <- Cars93[,c("EngineSize", "Horsepower", "RPM")]

lav.input<- cov(x)
lav.mean <- colMeans(x)

library(lavaan)
m1 <- 'EngineSize ~ Horsepower+RPM'
fit <- sem(m1, sample.cov = lav.input,sample.nobs = nrow(x), meanstructure = TRUE, sample.mean = lav.mean)
summary(fit, standardize=TRUE)

结果是:

Regressions:
                   Estimate    Std.Err  Z-value  P(>|z|)   Std.lv    Std.all
  EngineSize ~                                                              
    Horsepower          0.015    0.001   19.889    0.000      0.015    0.753
    RPM                -0.001    0.000  -15.197    0.000     -0.001   -0.576

Intercepts:
                  Estimate    Std.Err  Z-value  P(>|z|)   Std.lv    Std.all
   EngineSize          5.805    0.362   16.022    0.000      5.805    5.627

Variances:
                  Estimate    Std.Err  Z-value  P(>|z|)   Std.lv    Std.all
    EngineSize          0.142    0.021    6.819    0.000      0.142    0.133

答案 1 :(得分:1)

请记住:

$的β=(X'X)^ - 1。 X'Y $

尝试:

(bs<-solve(covx[-1,-1],covx[-1,1]))

 Horsepower         RPM 
 0.01491908 -0.00100051 

对于拦截,您需要变量的平均值。 例如:

  ms=colMeans(x)
  (b0=ms[1]-bs%*%ms[-1])

         [,1]
[1,] 5.805301

答案 2 :(得分:1)

我认为lavaan听起来是个不错的选择,我注意到@Philip指出了我正确的方向。我在这里只提一下如何使用你想要的lavaan(特别是r平方和调整的r平方)提取一些额外的模型特征。

有关最新版本,请参阅:https://gist.github.com/jeromyanglim/9f766e030966eaa1241f10bd7d6e2812

# get data
library(MASS)
data("Cars93")
x <- Cars93[,c("EngineSize", "Horsepower", "RPM")]

# define sample statistics 
covx <- cov(x)
n <- nrow(x)
means <- sapply(x, mean) # this is optional


fit <- lavaan::sem("EngineSize ~ Horsepower + RPM", sample.cov = covx,
                   sample.mean = means,
                    sample.nobs = n)

coef(fit) # unstandardised coefficients
standardizedSolution(fit) # Standardised coefficients
inspect(fit, 'r2') # r-squared

# adjusted r-squared
adjr2 <- function(rsquared, n, p) 1 - (1-rsquared)  * ((n-1)/(n-p-1))
# update p below with number of predictor variables
adjr2(inspect(fit, 'r2'), n = inspect(fit, "nobs"), p = 2) 

自定义功能

这里有一个功能可以提供来自lavaan的适合性以及一些相关的特征(即基本上包装了上面的大部分内容)。假设你没有办法。

covlm <- function(dv, ivs, n, cov) {
    # Assumes lavaan package
    # library(lavaan)
    # dv: charcter vector of length 1 with name of outcome variable
    # ivs: character vector of names of predictors
    # n: numeric vector of length 1: sample size
    # cov: covariance matrix where row and column names 
    #       correspond to dv and ivs
    # Return
    #      list with lavaan model fit
    #      and various other features of the model

    results <- list()
    eq <- paste(dv, "~", paste(ivs, collapse = " + "))
    results$fit <- lavaan::sem(eq, sample.cov = cov,
                       sample.nobs = n)

    # coefficients
    ufit <- parameterestimates(results$fit) 
    ufit <- ufit[ufit$op == "~", ]
    results$coef <- ufit$est
    names(results$coef) <- ufit$rhs

    sfit <- standardizedsolution(results$fit) 
    sfit <- sfit[sfit$op == "~", ]
    results$standardizedcoef <- sfit$est.std
    names(results$standardizedcoef) <- sfit$rhs

    # use unclass to not limit r2 to 3 decimals
     results$r.squared <- unclass(inspect(results$fit, 'r2')) # r-squared

    # adjusted r-squared
      adjr2 <- function(rsquared, n, p) 1 - (1-rsquared)  * ((n-1)/(n-p-1))
    results$adj.r.squared <- adjr2(unclass(inspect(results$fit, 'r2')), 
                                n = n, p = length(ivs)) 
    results

}

例如:

x <- Cars93[,c("EngineSize", "Horsepower", "RPM")]
covlm(dv = "EngineSize", ivs = c("Horsepower", "RPM"),
      n = nrow(x), cov = cov(x))

这一切都产生:

$fit
lavaan (0.5-20) converged normally after  27 iterations

  Number of observations                            93

  Estimator                                         ML
  Minimum Function Test Statistic                0.000
  Degrees of freedom                                 0
  Minimum Function Value               0.0000000000000

$coef
 Horsepower         RPM 
 0.01491908 -0.00100051 

$standardizedcoef
Horsepower        RPM 
 0.7532350 -0.5755326 

$r.squared
EngineSize 
     0.867 

$adj.r.squared
EngineSize 
     0.864 

答案 3 :(得分:0)

另一种时髦的解决方案是生成与原始数据具有相同方差 - 协方差矩阵的数据集。您可以使用mvrnorm()包中的MASS执行此操作。在这个新数据集上使用lm()将产生与从原始数据集估计的参数估计和标准误差相同的参数估计和标准误差(截距除外,除非您拥有每个变量的平均值,否则无法访问)。以下是一个示例:

#Assuming the variance covariance matrix is called VC
n <- 100 #sample size
nvar <- ncol(VC)
fake.data <- mvrnorm(n, mu = rep(0, nvar), sigma = VC, empirical = TRUE)
lm(Y~., data = fake.data)