【发布时间】:2019-12-10 23:32:48
【问题描述】:
每次在实验室分析样品时,我都需要使用线性回归模型创建单独的标准曲线。下面的代码使我可以过滤掉每个日期的观察结果,然后将该数据框插入回归模型并绘图,以便我得到该日期的标准曲线,显示曲线的 R 平方值和方程。
我的数据可以在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))
我想编写一个循环,为每个日期运行线性回归,然后让 R 使用 facet_wrap(~date) 为每个日期提供一个图表,并在每个图表上显示 R 平方值和回归方程。
【问题讨论】: