knitr::opts_chunk$set(echo = TRUE)
if(!require("pacman"))
  install.packages("pacman")
## Loading required package: pacman
library("pacman")
p_load("vroom",
       "ggplot2",
       "dplyr",
       "ggrepel",
       "tidyverse",
       "scales")

#Llamar a la base de datos

Datos_PCR <-vroom("https://raw.githubusercontent.com/ManuelLaraMVZ/resultados_PCR_practica/refs/heads/main/Cts1.csv")
## Rows: 32 Columns: 5
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (4): Well, Grupo, Practica, Fluor
## dbl (1): Cq
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
Datos_PCR
## # A tibble: 32 × 5
##    Well     Grupo Practica Fluor    Cq
##    <chr>    <chr> <chr>    <chr> <dbl>
##  1 A01      G1    Relativa SYBR   30.8
##  2 B01      G1    Relativa SYBR   41  
##  3 C01      G1    Relativa SYBR   26.1
##  4 D01      G1    Relativa SYBR   41  
##  5 E01      G1    Relativa SYBR   41  
##  6 F01      G1    Relativa SYBR   22.3
##  7 Profesor G1    Relativa SYBR   30.7
##  8 Profesor G2    Relativa SYBR   30.7
##  9 B01      G2    Relativa SYBR   20.3
## 10 C01      G2    Relativa SYBR   18.7
## # ℹ 22 more rows

#Filtrado de datos

Datos_curva <- Datos_PCR %>% 
  filter(Practica == "Absoluta",
         Grupo == "Curva") %>% 
  select("Well","Cq") %>% 
  mutate(Well = as.numeric(Well),
         Curva = Well,
         LogConc = log10(Curva)) %>% 
  select(3,4,2)
Datos_curva
## # A tibble: 7 × 3
##      Curva LogConc    Cq
##      <dbl>   <dbl> <dbl>
## 1 1000           3  12.4
## 2  100           2  15.6
## 3   10           1  18.8
## 4    1           0  22  
## 5    0.1        -1  25.2
## 6    0.01       -2  28.4
## 7    0.001      -3  34.8

#Gráfica de datos

Grafica <- ggplot(Datos_curva,
                 aes(x = LogConc,
                     y = Cq))+
  geom_point(color = "#2392e6", size = 4)+
  theme_classic()
Grafica

#Realizar el ajuste linear

modelo_lineal <- lm (data = Datos_curva, Cq ~ LogConc)

modelo_lineal
## 
## Call:
## lm(formula = Cq ~ LogConc, data = Datos_curva)
## 
## Coefficients:
## (Intercept)      LogConc  
##      22.457       -3.543

#Obtención de coeficientes

coeficientes <- coef(modelo_lineal)
coeficientes
## (Intercept)     LogConc 
##   22.457143   -3.542857
pendiente <- round (coeficientes [2], 2)
pendiente
## LogConc 
##   -3.54
y0 <- round(coeficientes [1],2)
y0
## (Intercept) 
##       22.46
prediccion <- data.frame (LogConc = seq(min(Datos_curva$LogConc), max(Datos_curva$LogConc), lenght.out = 100))
## Warning: In seq.default(min(Datos_curva$LogConc), max(Datos_curva$LogConc), 
##     lenght.out = 100) :
##  extra argument 'lenght.out' will be disregarded
prediccion$Cq <- predict(modelo_lineal, newdata = prediccion)
head(prediccion)
##   LogConc       Cq
## 1      -3 33.08571
## 2      -2 29.54286
## 3      -1 26.00000
## 4       0 22.45714
## 5       1 18.91429
## 6       2 15.37143

#Obtenemos el valor de R2

resumen_modelo <- summary(modelo_lineal)

resumen_modelo
## 
## Call:
## lm(formula = Cq ~ LogConc, data = Datos_curva)
## 
## Residuals:
##       1       2       3       4       5       6       7 
##  0.5714  0.2286 -0.1143 -0.4571 -0.8000 -1.1429  1.7143 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  22.4571     0.3959   56.73 3.22e-08 ***
## LogConc      -3.5429     0.1979  -17.90 1.00e-05 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 1.047 on 5 degrees of freedom
## Multiple R-squared:  0.9846, Adjusted R-squared:  0.9816 
## F-statistic: 320.3 on 1 and 5 DF,  p-value: 9.997e-06

#Obtener el valor de R²

R2 <- resumen_modelo$r.squared

R2
## [1] 0.9846311

#Queremos la ecuacion para publicarla en la gráfica

ecuacion_recta <- paste0("y = ", pendiente, "x + ", y0, "\nR² = ", round(R2, 3))
cat(ecuacion_recta)
## y = -3.54x + 22.46
## R² = 0.985

#Grafica del ajuste y de la ecuacion

Grafica_ajuste <- Grafica +
  geom_line(data = prediccion,
            aes(x = LogConc, y = Cq),
            color = "#e6c723",
            size = 1.5)+
  labs(title = "Curva estándar de RT-PCR",
       subtitle= "Equipo: LANS",
       caption = "Diseñó: Nicole Castañeda y Ana Elena Sordo",
       x= "Log10 (Concentración) [pg/μL)",
       y = "Cycle threshold (Ct)" )+
  theme_classic(base_size = 15)+
  scale_y_continuous(labels = number_format(accuracy = 1))+
  theme(plot.title = element_text(hjust= 0.5, face = "bold"),
        axis.title.x = element_text(face = "bold"),
        axis.title.y = element_text(face = "bold"))+
  annotate("text",
           x = max(Datos_curva$LogConc) -2,
           y = min(Datos_curva$Cq) + 20,
           label = ecuacion_recta,
           color = "#6e1d81",
           size = 5, 
           fontface = "bold",
           hjust = 0)
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
Grafica_ajuste

#Predicción de la concentración de la muestra tomando en cuenta la pendiente

Dato_muestra <- Datos_PCR %>% 
  filter(Practica == "Absoluta",
         Grupo == "G1",
         Well == "D01") %>% 
  select("Well", "Cq")

Dato_muestra
## # A tibble: 1 × 2
##   Well     Cq
##   <chr> <dbl>
## 1 D01    19.6

#Obtener el valor de Ct

Ct_muestra <- round(Dato_muestra$Cq, 2)
Ct_muestra
## [1] 19.63

#Obtener el valor de x (logConc)

LogConc_calculado <- (Ct_muestra-y0)/ pendiente

LogConc_calculado
## (Intercept) 
##    0.799435

#Valor real

Valor_real <- 10^LogConc_calculado

cat("La concentración de la muestra es:", round(Valor_real,2), "pg/µL")
## La concentración de la muestra es: 6.3 pg/µL

#Contrucción de dataframe

Datos_muestra <- data.frame(Concentracion_real = round(Valor_real,2),
                            LogConc = round(LogConc_calculado,2),
                            Cq = Ct_muestra)
Datos_muestra
##             Concentracion_real LogConc    Cq
## (Intercept)                6.3     0.8 19.63

#Gráfica de la muestra

Grafica_muestra <- Grafica_ajuste+ 
  geom_point(data = Datos_muestra,
             aes(x = LogConc,
                 y = Cq),
             color = "red",
             size = 6,
             shape = 20)+
  geom_segment(aes(x = min(Datos_curva$LogConc),xend= LogConc_calculado,
                   y = Ct_muestra, yend= Ct_muestra),
               linetype = "dotted", 
               color = "#7e6583",
               size = 1.5)+ 
  geom_segment(aes(x = LogConc_calculado, xend = LogConc_calculado,
                   y = min(Datos_curva$Cq), yend = Ct_muestra),
               linetype = "dotted",
               color = "#7e6583", 
               size = 1.5)+
  annotate("text",
           x = LogConc_calculado,
           y = Ct_muestra,
           label = paste0("[Muestra] = ", round(Valor_real,2), " pg/µL"),
           color = "black",
           fontface = "bold",
           hjust = -0.007,
           vjust = -1.5)

Grafica_muestra
## Warning: Use of `Datos_curva$LogConc` is discouraged.
## ℹ Use `LogConc` instead.
## Warning in geom_segment(aes(x = min(Datos_curva$LogConc), xend = LogConc_calculado, : All aesthetics have length 1, but the data has 7 rows.
## ℹ Please consider using `annotate()` or provide this layer with data containing
##   a single row.
## Warning: Use of `Datos_curva$Cq` is discouraged.
## ℹ Use `Cq` instead.
## Warning in geom_segment(aes(x = LogConc_calculado, xend = LogConc_calculado, : All aesthetics have length 1, but the data has 7 rows.
## ℹ Please consider using `annotate()` or provide this layer with data containing
##   a single row.