Search code examples
rcsvcorrelationglm

Export GLM Coefficients of Correlation to csv in R


After running my GLM model in R, I run the summary command with corr=TRUE to get the coefficients of correlation for the various variables in my model. What I would like to do is output those to a CSV file so I can open them in Excel.

I've tried using the coef command as well as several other methods I've found on this site for writing model output to a csv file. So far, I haven't had any luck getting the coefficients of correlation, just the Estimate, Std. Error, t value and p value.


Solution

  • You can use capture.output(). Assume model is your GLM:

    capture.output(summary(model, corr = TRUE), file = "filename.csv")
    

    This takes the exact text of the summary and writes it to a file.

    Update

    To get just the correlation coefficients, you can access the correlation element of the summary object (only works when corr = TRUE):

    df = data.frame(a = runif(100), b = runif(100))
    model <- glm(a ~ b, data = df)
    
    s <- summary(model, corr = TRUE)
    s$correlation
    
    #>             (Intercept)          b
    #> (Intercept)   1.0000000 -0.8334063
    #> b            -0.8334063  1.0000000
    

    You can take this output and write it to a csv which should preserve the table-like structure:

    write.csv(s$correlation, file = "filename.csv")
    

    Here is the documentation for summary.glm which shows the different members of the list that can be extracted.

    correlation
    (only if correlation is true.) The estimated correlations of the estimated coefficients.