首页 文章

相关矩阵

提问于
浏览
2

我是使用R的新手,我正在尝试创建一个相关矩阵 . 我有三个独立变量(x1,x2,x3)和一个从属变量(y) .

我一直在尝试使用cor来 Build 相关矩阵,但到目前为止,我已经无法找到这样做的公式 .

3 回答

  • 1
    x1=rnorm(20)
    x2=rnorm(20)
    x3=rnorm(20)
    y=rnorm(20)
    data=cbind(y,x1,x2,x3)
    cor(data)
    
  • 2

    如果我已经正确理解,你有一个3列的矩阵(比如说x1到x3)和很多行(作为y值) . 您可以采取以下行动:

    foo = matrix(runif(30), ncol=3) # creating a matrix of 3 columns
    cor(foo)
    

    如果你已经在3个向量x1到x3中的值,你可以像这样制作 foofoo=data.frame(x1,x2,x3)

  • 1

    如果我错了,请纠正我,但假设这与回归问题有关,这可能就是你要找的:

    #Set the number of data points and build 3 independent variables
    set.seed(0)
    numdatpoi <- 7
    x1 <- runif(numdatpoi)
    x2 <- runif(numdatpoi)
    x3 <- runif(numdatpoi)
    
    #Build the dependent variable with some added noise
    noisig <- 10
    yact <- 2 + (3 * x1) + (5 * x2) + (10 * x3)
    y <- yact + rnorm(n=numdatpoi, mean=0, sd=noisig)
    
    #Fit a linear model
    rmod <- lm(y ~ x1 + x2 + x3)
    
    #Build the variance-covariance matrix.  This matrix is typically what is wanted.
    (vcv <- vcov(rmod))
    
    #If needed, convert the variance-covariance matrix to a correlation matrix
    (cm <- cov2cor(vcv))
    

    从上面,这里是方差 - 协方差矩阵:

    (Intercept)        x1        x2        x3
    (Intercept)    466.5773   14.3368 -251.1715 -506.1587
    x1              14.3368  452.9569 -170.5603 -307.7007
    x2            -251.1715 -170.5603  387.2546  255.9756
    x3            -506.1587 -307.7007  255.9756  873.6784
    

    而且,这是相关的相关矩阵:

    (Intercept)          x1         x2         x3
    (Intercept)  1.00000000  0.03118617 -0.5908950 -0.7927735
    x1           0.03118617  1.00000000 -0.4072406 -0.4891299
    x2          -0.59089496 -0.40724064  1.0000000  0.4400728
    x3          -0.79277352 -0.48912986  0.4400728  1.0000000
    

相关问题