【问题标题】:matrix of correlations相关矩阵
【发布时间】:2012-11-04 17:01:42
【问题描述】:

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

我一直在尝试使用 cor 来制作相关矩阵,但到目前为止我还无法找到这样做的公式。

【问题讨论】:

    标签: r matrix


    【解决方案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
    

    【讨论】:

    • 为什么投反对票?问题的编写方式暗示了典型回归问题的可能性。
    【解决方案2】:
    x1=rnorm(20)
    x2=rnorm(20)
    x3=rnorm(20)
    y=rnorm(20)
    data=cbind(y,x1,x2,x3)
    cor(data)
    

    【讨论】:

    • 谢谢!这行得通!我必须做笔记并保留它,这比我尝试使用的过程要容易得多。
    【解决方案3】:

    如果我理解正确,您有一个 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)

    【讨论】:

    • 感谢您的建议。这实际上确实很好用,尽管对于一个稍微不同的问题(我也试图弄清楚)。谢谢!
    猜你喜欢
    • 2019-04-15
    • 2012-10-01
    • 2013-09-15
    • 2021-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多