---
title: "Novopsycovid"
author: "Philippe MICHEL"
date: "`r format(Sys.Date(),'%d %B %Y')`"
output:
  pdf_document:
    includes: null
    keep_tex: yes
    latex_engine: lualatex
    toc: yes
  html_document:
    df_print: paged
    toc_float: yes
    theme: lumen
    anchor_sections: yes
  html_notebook:
    fig_caption: yes
    theme: spacelab
  prettydoc::html_pretty:
    theme: architect
    highlight: github
    toc: yes
  word_document:
    toc: yes
subtitle: Quelques chiffres
editor_options:
  chunk_output_type: console
---

```{r setup, include= FALSE}
knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, cache = FALSE)
# knitr::opts_chunk$set(echo = TRUE, warning = FALSE, message = FALSE)
rm(list = ls())
expx = FALSE
```

```{r info}
library(forcats)
library(ggplot2)
library(epiDisplay)
library(lubridate)
library(tidyverse)
library(questionr)
library(plotly)
library(binom)
library(knitr)
library(see)
library(kableExtra)
library(baseph)
# sessionInfo()
```
```{r macros}
tabcx <- function(dfx,
                   tri,
                   nomv,
                   titre = "Tableau comparatif",
                   lab = "tabcomp",
                   export = FALSE) {
  # On supprime les données manquantes dans la variable de tri
  dfx <- as_tibble(dfx)
  dfx <- dfx %>%
    dplyr::filter(!is.na({{tri}}))
  var2 <- "+ age+profession, data = tt, family = binomial)"
  #
  tabx <- NULL
  nlig <- 0
  ligd <- NULL
  trix <- enquo(tri)
  vv <- quo_name(trix)
  triz <- dfx[vv]
  triz <- triz[[1]]
  for (ll in seq_len(length(dfx))) {
    varx <- dfx[, ll]
    varx <- varx[[1]]
    if (names(dfx)[ll] != vv) {
      nom <- paste0("<b>", nomv[ll], "</b>")
      var1 <-  paste0("glm(",vv,"~")
      aa <- paste0(var1,names(dfx)[ll],var2)
      ll <- eval(parse(text = aa))
      dd <- logistic.display(ll, simplified = TRUE)
      dd <- dd$table
      if (is.numeric(varx)) {
        # Variables numériques
        lig <- lignumc(nom, varx, triz)
        lig <- c(lig,beaup(dd[1,4]))
        tabx <- rbind(tabx, lig)
        nlig <- nlig + 1
      } else {
        # Variables factorielles
        if(is.factor(varx)==FALSE){
          varx <- as.factor(varx)
        }
        lig <- ligfcx(nom, varx, triz,beaup(dd[1,4]))
        tabx <- rbind(tabx, lig)
        llx <- length(levels(varx))
        nlig <- nlig + 1 + llx
        ligd <- c(ligd, seq(nlig - llx + 1, nlig))
      }
    }
  }
  # Export
  if (export) {
    nomcsv <- paste0(titre, "_export_comparatif.csv")
    write.csv(tabx, nomcsv)
  }
  # Création tableaux
  ltit <- c(" ", levels(triz), "p brut", "p ajusté")
  tabf <-   kable(
    tabx,
    row.names = FALSE,
    col.names = ltit,
    caption = titre,
    label = lab,
    escape = FALSE
  ) %>%
    kable_styling(
      bootstrap_options = "striped",
      full_width = FALSE,
      position = "center"
    )
  
  if (!is.null(ligd)) {add_indent(tabf, ligd)}
  #tabf %>%
   # scroll_box(width = "100%", height = "850px")

}    
######

ligfcx <- function(nom, varp, trip ,bdd) {
  tabp <- table(varp, trip)
  chip <- chisq.test(tabp, correct = TRUE)[[3]]
  chip <- chisq.test(tabp, correct = FALSE)
  if (min(chip$expected)<5){chip <- chisq.test(tabp, correct = TRUE)}
  chip <- chip[[3]]
  if (is.na(chip)){
    chip <- fisher.test(tabp)[[1]]
  }
  chip <- beaup(chip)
  ltri <- length(levels(trip))
  lvar <- length(levels(varp))
  tabg <- c(nom, rep(" ", ltri), chip,bdd)
  #
  ss <- colSums(tabp)
  for (lig in 1:lvar) {
    ligt <- levels(varp)[lig] 
    for (cas in 1:ltri) {
      casx <- tabp[lig, cas]
      casp <- round(100*casx/ss[cas],1)
      cast <- paste0(casx,"/",ss[cas]," (",casp," %)" )
      ligt <- c(ligt,cast)
    }
    ligt <- c(ligt, " ", " ")
    tabg <- rbind(tabg, ligt)
  }
  return(tabg)
}

##
graphconfx <- function(fdx,varx, vars, tit = " ",titx= "", tity = "%") {
tabx <- fdx  %>%
  summarise(tabx = table({{varx}},{{vars}}))
nnx <- fdx %>% 
  summarise(levels({{varx}}))
tabx <- as.matrix(tabx)
stabx <- rowSums(tabx)
tabo <- as.matrix(tabx)[,2]
tabz <- binom.confint(tabo,stabx, method = "exact")
tabz <- tibble(tabz[,4:6])
tabz <- bind_cols(tabz,nnx)
names(tabz)[4] <- "names"
#return(tabz)
#
tabz %>% 
  ggplot() +
  aes(x = names, y = mean*100, fill = names) +
  geom_bar(stat = "identity")  +
geom_errorbar(aes(ymin = lower * 100, ymax = upper * 100),
              width = .2,
              position = position_dodge(.9)) +
  labs(title = tit,
       subtitle = "",
       x = titx,
       y = tity,
       caption = tit,
       label = "stress1") +
  theme_light() +
  scale_fill_material() +
  theme(
    plot.title = element_text(size = 18, face = "bold"),
    plot.subtitle = element_text(size = 12),
    axis.title.x = element_text(size = 12),
    axis.title.y = element_text(
      size = 12,
      angle = 90,
      vjust = .5
    ),
    axis.text.x = element_text(
      size = 12 ,
      angle = 0,
      hjust = 0.5
    ),
    axis.text.y = element_text(size = 12),
    legend.position = "none"
  )
}
```




```{r import}
  tt <- debutph("data/NOVOPSYCOVID.csv")
tt$age <- as.numeric(str_sub(tt$age,1,2))
tt$mois.hospitalisation <- as.factor(ifelse(tt$mois.hospitalisation %in% c("mars-20","avr.-20"), "mars-avril","mai-juin"))
tt$mois.hospitalisation <- fct_relevel(tt$mois.hospitalisation ,"mars-avril")
tt$satisfaction.hospitalisation <- fct_relevel(tt$satisfaction.hospitalisation,c("Très insatisfait","Insatisfait","Mitigé","Satisfait","Très satisfait"))
#
bt <- read.csv("data/titre.csv")
btitre <- bt$titre 
```
Les données à réponses ouvertes n'ont pas été traitées. 

## Description de la population

La base comprend `r dim(tt)[1]` sujets pour `r dim(tt)[2]` variables.

### Pyramide des âges

```{r pyramid}
pyramid(tt$age,tt$sexe,col.gender = c("pink","blue"), main = "Pyramide des âges", binwidth = 10)
``` 

### Tableaux descriptifs

```{r tableau}
tab1ph(tt[,c(1:7)],btitre[c(1:7)], titre = "Données démographiques", label = "tab11", export = expx)

tab1ph(tt[,c(8:17)],btitre[8:17], titre = "Situation actuelle", label = "tab12", export = expx)

tab1ph(tt[,c(18:23)],btitre[18:23], titre = "Au retour à domicile", label = "tab13", export = expx)

tab1ph(tt[,c(24:27)],btitre[24:27], titre = "Projection à venir", label = "tab14", export = expx)
```

## Analyses

### Selon la période

```{r periodetab}
tabcx(tt,mois.hospitalisation, btitre, titre = "Périodes d'hospitalisation", export = expx)
zzx <- as.data.frame(tt)
glmph(dfx="zzx",vart="mois.hospitalisation",vars=c("age","duree.de.sejour","troubles.appetit","guerison.avec.sequelles", "apprehension.contamination.autrui" ), bnom = btitre, titre = "Période de l'hospitalisation - analyse multivariée", export = expx)
```
La seule différence notable entre les deux périodes (mars-avril & mai-juin 2020) est la durée de séjour. On observe sur les conséquences psychologiques une seule différence significative sur les troubles de l'appétit, isolée, probablement accidentelle. En analyse multivariée par régression logistique on ne retrouve une différence que sur la durée de séjour.

Il a été impossible d’incorporer la profession dans l'analyse en régression.

```{r periodegraph1}
tt %>% 
  ggplot() +
  aes(x= mois.hospitalisation, y = duree.de.sejour, fill = mois.hospitalisation) +
  geom_violin() +
  geom_boxplot(, width = 0.12, fill = "white") +
  geom_text(x= 1.5, y = 35, label = "p < 0,001", size =5) +
      labs(title = "Durée de séjour selon la période d'hospitalisation",
           subtitle = "2020",
           caption = "Durée de séjour selon la période d'hospitalisation (année 2020)",
           y = "jours",
           label = ("dsmois")) +
      theme_light() +
      scale_fill_material() +
      theme(
        plot.title = element_text(size = 18, face = "bold"),
        plot.subtitle = element_text(size = 12),
        axis.title.x = element_blank(),
        axis.title.y = element_text(
          size = 12
        ),
        axis.text.x = element_text(
          size = 12
        ),
        axis.text.y = element_text(size = 12),
        legend.position = "none"
      )
```

### Retour à domicile

La variable étudiée est *RAD au bon moment ?*.

Très peu de patients (3) ont répondu être rentré à domicile trop tard. On ne va donc comparer que *au bon moment" vs "précipité*.

```{r tab1rad}
zzx <- tt
zzx$rad.au.bon.moment[zzx$rad.au.bon.moment=="Trop tard"] <- NA
zzx$rad.au.bon.moment <- factor(zzx$rad.au.bon.moment)
tabcx(zzx,rad.au.bon.moment, nomv= btitre, titre = "Retour à domicile", export = expx)
zzx <- as.data.frame(zzx)
glmph(dfx="zzx",vart="rad.au.bon.moment",vars=c("age","profession","duree.de.sejour" ,"stress",  "troubles.attentionnels","besoin.voir.medecin","entourage.au.domicile","apprehension.sorties" ,"apprehension.reprise.travail"), bnom = btitre, titre = "Retour à domicile - analyse multivariée", export = expx)
```

```{r graphrad}
graphconfx(zzx,rad.au.bon.moment,stress, "Stress & retour à domicile", titx = "Retour à domicile", tity = "% stress")

graphconfx(zzx,rad.au.bon.moment,troubles.attentionnels, "Troubles attentionnels & retour à domicile", titx = "Retour à domicile",tity = "% troubles.attentionnels")

graphconfx(zzx,rad.au.bon.moment,besoin.voir.medecin, "Besoin de voir un médecin & retour à domicile", titx = "Retour à domicile",tity = "% besoin de voir un médecin")

graphconfx(zzx,rad.au.bon.moment, entourage.au.domicile, "entourage au domicile & retour à domicile", titx = "Retour à domicile",tity = "% entourage au domicile")

graphconfx(zzx,rad.au.bon.moment, apprehension.sorties, "Appréhension sorties & retour à domicile", titx = "Retour à domicile",tity = "% appréhension sorties")

graphconfx(zzx,rad.au.bon.moment, apprehension.reprise.travail, "Appréhension reprise travail & retour à domicile", titx = "Retour à domicile",tity = "% appréhension reprise travail")
```

