Save Linear Regression output r
I want to make a linear regression where my dependant variable is data$fs_deviation_score while independent vairables are multiple columns of my data frame (column 660 to 675).
with this function it works but i am not able to save the output (Coefficients : Estimate , Std.Error, p value..)
Reg<-lapply( data[660:675], function(x) summary(lm(data$fs_deviation_score ~ x)))
I search a function to save the output (Coefficients :Estimate, Std.Error, p value..)
Thanks
Solution 1:
If you have that Reg object produced by:
Reg<-lapply( data[660:675], function(x) summary(lm(data$fs_deviation_score ~ x)))
Then all you need to do to extract the coefficients matrix from each summary object is this:
CoefMats <- lapply( Reg, coef)
The summary-objects are actually named lists (as are lm and glm objects). ?summary.lm
will bring up the specific help page and the Value
subsection will give you all the names. The See Also
links should also be reviewed.
Had you want the r.squared values you could have use this:
Rsqds <- lapply(Reg, "[[", "r.squared")
Solution 2:
Example:
m <- lm (as.integer (Species), iris);
save (m, "iris_lm.RData");
Now in a new session.
load ("iris_lm.RData");
summary (m);
names (m);
You can use the save
function to save the entire object and read and use it later. Note that this is a general way to store any R object.
To be able to want to store the components of the components of the summary of the model m
. You can do as follows for example to store the residuals.
write.csv (m$residuals, "residuals.csv");
To access each components of the summary, execute names(m)
so see what are the components do help (summary.lm)
Solution 3:
If you want to save the output of the regression model in Tibble format, you can use the broom package. This works for other model objects too.
Also, gtsummary package helps to get output in presentation-ready table format. For examples; see this