#dificulto realizar las medidad sin el tiempo #Se necesita medir en el tiempo+ los sujetos -factores- (diseños) #medidas repetidas de una via, dos vias, tres vias #investigar con otro nombre()

#una via: UN SOLO FACTOR QUE ES EL TIEMPO, NINGUNA OTRA (tiempos equidistantes)- hay otro tratamiento con tiempos no equidistantes investigar este

#solo hay tiempo y respuesta
#quiero ver que pasa en el tiempo sobre este cultivo
#install.packages("datarium")
data("selfesteem", package = "datarium")
#hay un identificador de "parcelas"  (id)
datos = selfesteem
head(datos, 3)
##   id       t1       t2       t3
## 1  1 4.005027 5.182286 7.107831
## 2  2 2.558124 6.912915 6.308434
## 3  3 3.244241 4.443434 9.778410
datos
##    id       t1       t2       t3
## 1   1 4.005027 5.182286 7.107831
## 2   2 2.558124 6.912915 6.308434
## 3   3 3.244241 4.443434 9.778410
## 4   4 3.419538 4.711696 8.347124
## 5   5 2.871243 3.908429 6.457287
## 6   6 2.045868 5.340549 6.653224
## 7   7 3.525992 5.580695 6.840157
## 8   8 3.179425 4.370234 7.818623
## 9   9 3.507964 4.399808 8.471229
## 10 10 3.043798 4.489376 8.581100
boxplot(datos[,-1])

#construcción de los datos en formato largo (gather), pocas columnas
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(tidyr)
# install.packages("datarium")
data("selfesteem", package = "datarium")

datos = selfesteem
datos = datos  %>%
  gather(key = "tiempo",
         value = "rto",
         t1, t2, t3) %>%
  mutate_at(vars(id, tiempo), as.factor)
View(datos)

#resumen estadistico

#estilo del documento
datos %>%
  group_by(tiempo) %>%
  summarise(media = mean(rto),
            desv = sd(rto),
            n = n(),
            cv = 100*desv/media)
## # A tibble: 3 × 5
##   tiempo media  desv     n    cv
##   <fct>  <dbl> <dbl> <int> <dbl>
## 1 t1      3.14 0.552    10  17.6
## 2 t2      4.93 0.863    10  17.5
## 3 t3      7.64 1.14     10  15.0
#CV>20% los datos son normales, son buenos para analizar, homogeneidad.
#CV<20% Heterogeneidad, causante d eproblemas para analizar, se pueden imputar
boxplot(datos$rto~datos$tiempo)

#detencción de datos atipicos (outliers)

library(rstatix)
## 
## Attaching package: 'rstatix'
## The following object is masked from 'package:stats':
## 
##     filter
datos %>%
  group_by(tiempo) %>%
  identify_outliers(rto)
## # A tibble: 2 × 5
##   tiempo id      rto is.outlier is.extreme
##   <fct>  <fct> <dbl> <lgl>      <lgl>     
## 1 t1     6      2.05 TRUE       FALSE     
## 2 t2     2      6.91 TRUE       FALSE

#hay dos datos sospechosos, se parecen pero no lo son, no son preocupantes, tener cuidado con los EXTREMOS, eso si son datos atipicos.

#hipotesis \[H_0: \mu_1=\mu_2=\mu_3\]

datos %>%
  group_by(tiempo) %>%
  shapiro_test(rto)
## # A tibble: 3 × 4
##   tiempo variable statistic     p
##   <fct>  <chr>        <dbl> <dbl>
## 1 t1     rto          0.967 0.859
## 2 t2     rto          0.876 0.117
## 3 t3     rto          0.923 0.380
#no se rechaza, los datos tienen una distribución normal

#TEST DE MAUCHLY: supuesto de esfericidad SOLO PARA MEDIAS REPETIDAS (variabildiad en tiempos sucesivos) #tiene que ver con igualdad de varianzas

res_aov = anova_test(data=datos,
                     dv=rto,
                     wid=id,
                     within = tiempo)
res_aov
## ANOVA Table (type III tests)
## 
## $ANOVA
##   Effect DFn DFd      F        p p<.05   ges
## 1 tiempo   2  18 55.469 2.01e-08     * 0.829
## 
## $`Mauchly's Test for Sphericity`
##   Effect     W     p p<.05
## 1 tiempo 0.551 0.092      
## 
## $`Sphericity Corrections`
##   Effect  GGe      DF[GG]    p[GG] p[GG]<.05   HFe      DF[HF]    p[HF]
## 1 tiempo 0.69 1.38, 12.42 2.16e-06         * 0.774 1.55, 13.94 6.03e-07
##   p[HF]<.05
## 1         *
#p_valor>5% no se rechaza la H_0: hay esfericidad

res_aov$`Mauchly's Test for Sphericity`
##   Effect     W     p p<.05
## 1 tiempo 0.551 0.092
get_anova_table(res_aov)
## ANOVA Table (type III tests)
## 
##   Effect DFn DFd      F        p p<.05   ges
## 1 tiempo   2  18 55.469 2.01e-08     * 0.829
#rechazo la H_0: el aceite producido en los 3 diferentews tiempos es diferentes, el tiempo de corte tiene efecto 

#comparación entre tiempos aposteriori

datos%>%
  pairwise_t_test(
    rto ~ tiempo, paired = TRUE,
    p.adjust.method = "bonferroni")
## # A tibble: 3 × 10
##   .y.   group1 group2    n1    n2 statistic    df           p p.adj p.adj.signif
## * <chr> <chr>  <chr>  <int> <int>     <dbl> <dbl>       <dbl> <dbl> <chr>       
## 1 rto   t1     t2        10    10     -4.97     9 0.000772     2e-3 **          
## 2 rto   t1     t3        10    10    -13.2      9 0.000000334  1e-6 ****        
## 3 rto   t2     t3        10    10     -4.87     9 0.000886     3e-3 **
#prueba_bonferroni
#p_valor a usar AJUSTADO
#P_VALORES<5%: se rechaza H_0. todos son diferentes  

#medidas repetidas de dos vias: tiempo+ otro factor #f1: tiempo #f2: fertilidad

data("selfesteem2", package = "datarium")

datos2 = selfesteem2
View(datos2)

datos2 = selfesteem2
datos2$treatment = gl(2,12,24, c('con fert', 'sin fert'))
datos2 = datos2 %>% 
  gather(key='tiempo', value = 'rto',
         t1 ,t2 ,t3)
datos2
## # A tibble: 72 × 4
##    id    treatment tiempo   rto
##    <fct> <fct>     <chr>  <dbl>
##  1 1     con fert  t1        83
##  2 2     con fert  t1        97
##  3 3     con fert  t1        93
##  4 4     con fert  t1        92
##  5 5     con fert  t1        77
##  6 6     con fert  t1        72
##  7 7     con fert  t1        92
##  8 8     con fert  t1        92
##  9 9     con fert  t1        95
## 10 10    con fert  t1        92
## # ℹ 62 more rows

tabla resumen estadistico

datos2 %>%
  group_by(treatment, tiempo) %>%
  summarise(media = mean(rto),
            desv = sd(rto),
            n = n(),
            cv = 100*desv/media)
## `summarise()` has grouped output by 'treatment'. You can override using the
## `.groups` argument.
## # A tibble: 6 × 6
## # Groups:   treatment [2]
##   treatment tiempo media  desv     n    cv
##   <fct>     <chr>  <dbl> <dbl> <int> <dbl>
## 1 con fert  t1      88    8.08    12  9.18
## 2 con fert  t2      83.8 10.2     12 12.2 
## 3 con fert  t3      78.7 10.5     12 13.4 
## 4 sin fert  t1      87.6  7.62    12  8.70
## 5 sin fert  t2      87.8  7.42    12  8.45
## 6 sin fert  t3      87.7  8.14    12  9.28

#Resumen estadistico descriptivo

library(ggplot2)

ggplot(datos2)+
  aes(tiempo, rto, fill=treatment)+
  geom_boxplot()

#deteccion de datos atipicos (outlires)

datos2 %>%
  group_by(treatment, tiempo) %>%
  identify_outliers(rto)
## [1] treatment  tiempo     id         rto        is.outlier is.extreme
## <0 rows> (or 0-length row.names)

#analisis de varianza

res.aov <- anova_test(
  data = datos2,
  dv = rto,
  wid = id,
  within = c(treatment,
             tiempo)
  )
get_anova_table(res.aov)
## ANOVA Table (type III tests)
## 
##             Effect  DFn   DFd      F        p p<.05   ges
## 1        treatment 1.00 11.00 15.541 2.00e-03     * 0.059
## 2           tiempo 1.31 14.37 27.369 5.03e-05     * 0.049
## 3 treatment:tiempo 2.00 22.00 30.424 4.63e-07     * 0.050
#P_valor interacción; si hay interración: Se rechaza la H_0.
res.aov$`Mauchly's Test for Sphericity`
##             Effect     W     p p<.05
## 1           tiempo 0.469 0.023     *
## 2 treatment:tiempo 0.616 0.089
#

#analisis cuando hay interacción

#grafico de interacción

interaction.plot(datos2$tiempo,
                 datos2$treatment,
                 datos2$rto)

  datos2 %>% 
  group_by(tiempo, treatment) %>% 
  summarise(mean_rto = mean(rto)) %>% 
  ggplot()+
  aes(tiempo, mean_rto,
      color=treatment,
      group=treatment)+
  geom_point(size=5)+
  geom_line(linewidth=3)
## `summarise()` has grouped output by 'tiempo'. You can override using the
## `.groups` argument.

#conclusión: en el t1 no hay gran diferencia, el patro es diferente al t3, donde es mejor sin fert, si lo hace le hirá mal