'Extracting coefficients and r-squared from a list of linear models in R

I have created a list of dataframes by splitting my dataset by "Species". Then I used lapply to apply a lm to each dataframe and store it in a list of linear models. Now, what I want to do is to extract the coefficients, r-squared, and adjusted r-squared for each models and store them in a dataframe.

I have tried the following code:

# Objective 0: Group dataset by species and add new columns

*BT_logged <- BT_logged_mean %>% group_by(STUDY_ID,SPECIES) %>% mutate(maxYEAR = max(YEAR), minYEAR = min(YEAR), TS_length = length(unique(MEAN_MULT)), scaleabund = (ADJUSTED_ABUNDANCE- min(ADJUSTED_ABUNDANCE)) / (max(ADJUSTED_ABUNDANCE)- min(ADJUSTED_ABUNDANCE))) %>% filter(is.finite(scaleabund), TS_length > 5) %>% ungroup()*


# Objective1: Create a list of data frames by splitting the dataset by species

*TimeSeries_slist <- split(BT_logged, f = BT_logged$SPECIES)* 

# Objective2: Fit a linear model and extract model coefficients and store them into a data frame using lapply

*TimeSeries_escalist_lm <- lapply(TimeSeries_slist, function(x) lm(scaleabund ~ YEAR, data = x))
Models_scale_lapply <- filter(data.frame("SPECIES" = names(TimeSeries_escalist_lm), "n" = unlist(lapply(TimeSeries_escalist_lm, function(x) df.residual(x))), "intercept" = unlist(lapply(TimeSeries_escalist_lm, function(x) summary(x)$coeff[1])), "slope" = unlist(lapply(TimeSeries_escalist_lm, function(x) summary(x)$coeff[2])), "intercept_se" = unlist(lapply(TimeSeries_escalist_lm, function(x) summary(x)$coeff[3])), "slope_se" = unlist(lapply(TimeSeries_escalist_lm, function(x) summary(x)$coeff[4])), "intercept_p" = unlist(lapply(TimeSeries_escalist_lm, function(x) summary(x)$coeff[7])), "slope_p" = unlist(lapply(TimeSeries_escalist_lm, function(x) summary(x)$coeff[8])), "TS_length" = unlist(lapply(TimeSeries_slist, function(x) max((x)$TS_length)))), n > 5)*

However, when I tried to add to the code above the following code for r-squared or adjusted r-squared:

*"r_squared" = unlist(lapply(TimeSeries_escalist_lm, function(x) summary(x)$r.squared)*

I get the following error:

Error in unlist(lapply(TimeSeries_slist, function(x) max((x)$TS_length)),  : 
  unused argument (r2 = unlist(lapply(TimeSeries_escalist_lm, function(x) summary(x)$r.squared)))

Which I do not know how to correct.

Would anyone kindly help me to find an efficient way to extract coefficients and r-squared from a list of linear models.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source