Running multiple, simple linear regressions from dataframe in R

前端 未结 3 688
Happy的楠姐
Happy的楠姐 2021-02-06 12:04

I have a dataset (data frame) with 5 columns all containing numeric values.

I\'m looking to run a simple linear regression for each pair in the dataset.

For ex

3条回答
  •  时光取名叫无心
    2021-02-06 12:52

    I would recommend to also look at the correlation matrix (cor(DF)), which is usually the best way to discover linear relationships between variables. The correlation is tightly linked to the covariance and the slopes of a simple linear regression. The computation below exemplifies this link.

    Sample data:

    set.seed(1)
    DF <- data.frame(
      A=rnorm(50, 100, 3),
      B=rnorm(50, 100, 3),
      C=rnorm(50, 100, 3),
      D=rnorm(50, 100, 3),
      E=rnorm(50, 100, 3)
    )
    

    The regression slope is cov(x, y) / var(x)

    beta = cov(DF) * (1/diag(var(DF)))
    
                A            B           C           D           E
    A  1.00000000 -0.045548503 0.028448192 -0.32982367  0.01800795
    B -0.03354243  1.000000000 0.003298708 -0.02489518  0.04501362
    C  0.02429041  0.003824755 1.000000000  0.24269838  0.15550116
    D -0.22407592 -0.022967212 0.193107904  1.00000000 -0.08977834
    E  0.01038445  0.035248685 0.105020194 -0.07620397  1.00000000
    

    The intercept is mean(y) - beta * mean(x)

    colMeans(DF) - beta * colMeans(DF)
    
                 A         B         C         D         E
    A 1.421085e-14 104.86992  97.44795 133.38310  98.49512
    B 1.037180e+02   0.00000 100.02095 102.85026  95.83477
    C 9.712461e+01  99.16182   0.00000  75.38373  84.06356
    D 1.226899e+02 102.53263  80.87529   0.00000 109.22915
    E 9.886859e+01  96.38451  89.41391 107.51930   0.00000
    

提交回复
热议问题