R/get_tpc.R

Defines functions get_tpc

Documented in get_tpc

## * GET THERMAL PERFORMANCE CURVE

#' Get thermal performance curve
#'
#' Gets a thermal performance curve from a temperature and performance vectors.
#'
#' @param Tm A vector of temperature values
#'
#' @param P A vector of performance values
#'
#' @param Degree The degree of the polynomial regression used to fit the curve. If not specified the degree with lowest AIC is selected
#'
#' @param Pmin The minimum performance value.
#'
#' @return A dataset of four columns: "T" for temperautre, "P" for performance, "L" for the low 95% CI & "U" for the high 95% CI
#'
#' @examples
#'
#'@export

get_tpc <- function(Tm, P, Degree, Pmin){

  # Get the fit

  # If "Degree" is missing select the polynomial degree with the lowest AIC score
  if( missing (Degree)) {

    # Comparisons data frame
    C <- data.frame( deg = c(2:4), aic = rep(NA,3))

    # Fill dataframe with AIC values
    for(i in 1:nrow(C)){ C$aic[i] <- AIC(lm(P ~ poly(Tm, degree = i, raw =T)))}

    # Select best degeree
    best <- C %>% filter(aic == min(aic)) %>% filter(deg == min(deg)) %>% select(deg) %>% as.numeric()

    # Get the model fit with the best
    fit <- lm(P ~ poly(Tm, degree = best, raw = T))

    # If "Degree" not missing use it
  } else {

    fit <- lm(P ~ poly(Tm, degree = Degree, raw = T))

  }

  # Mock temperatures vector
  t <- data.frame(Tm = seq(min(Tm, na.rm = T) - 1, max(Tm, na.rm = T) + 1 , by = 0.01))

  # Get fit predictions as well as lwr & upr 95% CIs
  tpc <- predict(fit, t, interval = "confidence")

  # Merge together
  tpc <- cbind(t, tpc)

  # Rename columns
  tpc <- rename(tpc, P = fit, L = lwr, U = upr)

  # Filter P < Pmin columns
  tpc <- filter(tpc, P >= Pmin)

  return(tpc)

}
ggcostoya/tpcurves2 documentation built on Jan. 1, 2021, 2:19 a.m.