Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201839

Create a Loop that creates a linear regressions for each date

$
0
0

Every time I analyze samples in the lab, I need to create a separate standards curve using a linear regression model. The code below makes it such that I can filter out observations for each date and then plug in that data frame into the regression model and plot so that I get a standard curve for that date that displays the R squared value and equation for the curve.

My data can be found at https://github.com/derekpagenkopp/ghg_flux

#------------------------------------------
# Load packages
library(tidyverse)
library(here)


#-------------------------------------------
# Read in data

ch4_standards <- read_csv(here::here("data",
                                     "ch4_standard_raw.csv"))

#-------------------------------------------
# Use lm(), linear model function, to create regression model

### Change dates in name and filter

fit_ch4_20190830 <- lm(ppm ~ area, data = ch4_standards %>% filter(date == "2019_08_30"))

#-------------------------------------------
#Use summary function to get summary information about linear model

### Changes dates

summary(fit_ch4_20190830)

#--------------------------------------------
#Function to create standard curve
### Change date in labs

ggplot_regression <- function (fit) {

  require(ggplot2)

  ggplot(fit$model, aes_string(x = names(fit$model)[1], y = names(fit$model)[2])) + 
    geom_point() +
    stat_smooth(method = "lm", col = "red") +
    labs(title = "20190830 CH4 Standard Curve", caption = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared, 5),
                                                                "Intercept =",signif(fit$coef[[1]],5 ),
                                                                " Slope =",signif(fit$coef[[2]], 5),
                                                                " P =",signif(summary(fit)$coef[2,4], 5)))
}

### Change date in filter




ggplot_regression(lm(ppm ~ area, data = ch4_standards %>% 
                       filter(date == "2019_08_30")))+
  coord_flip()+
  theme_classic()+
  theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        plot.title = element_text(hjust = 0.5),
        title = element_text(vjust=3))

I would like to write a loop that will run the linear regression for each date, then have R give a graph for each date using facet_wrap(~date) and that displays the R squared value and the regression equation on each graph.


Viewing all articles
Browse latest Browse all 201839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>