Search code examples
rcbind

Column-by-Column cbind of lm output


I'd like to do a column-by-column comparison of two lm outputs. Something like this except I'd like to see the estimates next to the estimates nest to the estimates, the Std Error next to the Std Error, etc.

    x=runif(6);y=runif(6);z=runif(6)
    x2=runif(6);y2=runif(6);z2=runif(6)
    lm1=lm(x~z+y)
    lm2=lm(x2~z2+y2)
    s=summary(lm1)[["coefficients"]]
    s2=summary(lm2)[["coefficients"]]
    > cbind(s,s2)
               Estimate Std. Error    t value  Pr(>|t|)   Estimate Std. Error   t value   Pr(>|t|)
(Intercept)  0.67359508  0.8137390  0.8277778 0.4684978  0.6944551  0.2398032  2.895938 0.06270911
z           -0.19911923  1.0491558 -0.1897899 0.8615892  1.2509814  0.5678805  2.202896 0.11486078
y           -0.07097291  0.4569228 -0.1553280 0.8864254 -0.8926959  0.4984554 -1.790924 0.17123009

Solution

  • Try this:

    # column bind
    res <- cbind(s,s2)
    
    # make unique column names
    colnames(res) <- make.unique(colnames(res))
    
    # sort column names
    ix <- order(colnames(res))
    
    # result
    res[,ix]
    
    # output
    
    #               Estimate Estimate.1  Pr(>|t|) Pr(>|t|).1 Std. Error Std. Error.1    t value t value.1
    # (Intercept)  1.7701957 0.09783934 0.5505218  0.7042956  2.6399847    0.2342630  0.6705325 0.4176475
    # z            0.2393442 0.45691026 0.8111899  0.6096530  0.9180588    0.8041508  0.2607068 0.5681898
    # y           -1.7020430 0.12906057 0.6185858  0.8798162  3.0758497    0.7846930 -0.5533570 0.1644727