0

I am summing data over different time intervals via a loop, and at the end, I'm running it through a linear model. Currently, I'm hardcoding in all the coefficients I want and appending them to a data frame, and once the loop is over, it's exporting a CSV.

The issue is, I have a lot of variables, and would like to export all of them for each iteration.

Is there a way to do this? Ideally, I'd like to pull the coefficients for each independent variable, the P-value of each independent, P-value of the model, and adjusted R2 of the model, and export

Any ideas? This is what the loop looks like:

outputs <- matrix(,ncol=4)

for(size in seq(20,30, by= 10))
{ 
for(i in 2:nrow(df_first))   
{ upperWindow <- as.numeric(df_first$time) <= 
(as.numeric(perf$time[i])+g*60)
lowerWindow <- df_first$time >= perf$time[i]      
total[i] <- sum(perf$total [upperWindow & lowerWindow])
}
fit <- lm(total ~ x + y) 

model_coef <- coefficients$fit 

outputs <- rbind(model_coef, size, fit$adj.r.squared)
} 
write.table (outputs, file =~ ) 

Basically, I would like to pull all the coefficients, Rsquareds, and size out of the models I'm running, and export them to a CSV. I keep getting the error message "attributes are not identical across measure variables; they will be dropped"

Julia
  • 176
  • 2
  • 12
  • shouldn't be hard, but please post a minimal reproducible example. Are you using lm(), glm() or something else to solve the linear model. answer depends on these details. – dww Apr 07 '16 at 00:26
  • Possible duplicate of [pull out p-values and r-squared from a linear regression](http://stackoverflow.com/questions/5587676/pull-out-p-values-and-r-squared-from-a-linear-regression) – dww Apr 07 '16 at 17:29

1 Answers1

0

No reproducible example was provided so here is a generic example of how to extract the desired values from your linear model:

ctl <- c(4.17,5.58,5.18,6.11,4.50,4.61,5.17,4.53,5.33,5.14)
trt <- c(4.81,4.17,4.41,3.59,5.87,3.83,6.03,4.89,4.32,4.69)
group <- gl(2, 10, 20, labels = c("Ctl","Trt"))
weight <- c(ctl, trt)
fit <- lm(weight ~ group)
sumfit <- summary(fit)

we can get the coefficients from fit either using the coefficients method, or using $ as in

coeffs <- fit$coefficients

and summary statistics as follows

r.squared <- sumfit$r.squared  # r squared
adj.r.sq <- sumfit$adj.r.squared # adjusted r squared
coeff.p <- sumfit$coefficients[,4] # p values for each coefficient

other values from fit and sumfit can be extracted in similar manner. Take a look at their values to see what is available.

dww
  • 30,425
  • 5
  • 68
  • 111