
<div style="display:block;clear:both;" class="rosetta-descr-start"></div>
<div class="rosetta-descr-container">

```{r,eval=TRUE, echo=FALSE}

labels <-
  c(mean = "Mean",
    median = "Median",
    mode = "Mode",
    var = "Variance",
    sd = "Standard Deviation",
    se = "Standard Error",
    min = "Minimum",
    max = "Maximum",
    q1 = "First quartile",
    q3 = "Third quartile",
    IQR = "Interquartile range",
    skewness = "Skewness",
    kurtosis = "Kurtosis",
    dip = "Dip test",
    meanCI = paste0(100 * attr(x, 'conf.level'), "% Conf. Interval"),
    totalN = "Total sample size",
    missingN = "Missing values",
    validN = "Valid sample size"
  );

maxPlotCols <- attr(x, "maxPlotCols");
show <- attr(x, "show");

if ("rosettaDescriptives" %in% class(x)) {
  frequencies <- FALSE;
  singleDescriptives = FALSE;
  multipleDescriptives = TRUE;
} else if ("freq" %in% class(x)) {
  frequencies <- TRUE;
  singleDescriptives = FALSE;
  multipleDescriptives = FALSE;
  chartType <- "Bar chart";
  varName <-
    ifelse(
      is.null(attr(x, "varLabel")) || is.na(attr(x, "varLabel")),
      attr(x, "varName"),
      attr(x, "varLabel")
    );
} else {
  frequencies <- FALSE;
  singleDescriptives = TRUE;
  multipleDescriptives = FALSE;
  chartType <- "Histogram";
  varName <- row.names(x);
}

oldKableViewOption <- getOption("kableExtra_view_html", NULL);
options(kableExtra_view_html = FALSE);

oldKnitrKableNAOption <- getOption("knitr.kable.NA", NULL);
options(knitr.kable.NA = '')

if (!exists('headingLevel') || !is.numeric(headingLevel) || (length(headingLevel) != 1)) {
  headingLevel <- 0;
}

```

```{r, results='asis', eval=frequencies}

ufs::heading("Frequencies for ", varName,
             headingLevel=headingLevel);
```

```{r, results='asis', eval=singleDescriptives}
ufs::heading("Descriptives for ", varName,
             headingLevel=headingLevel);
```

```{r, results='asis', eval=multipleDescriptives}
ufs::heading("Descriptives for variables in data frame ", attr(x, "datasetName"),
             headingLevel=headingLevel);
```

```{r, echo=echoPartial, results='asis', eval=frequencies}

ufs::kblXtra(
  x$dat,
  row.names = TRUE,
  escape = TRUE
);

```

```{r, echo=echoPartial, results='asis', eval=singleDescriptives}

formattedDescriptives <- c();
for (i in intersect(show, names(x))) {
  if ((is.character(x[, i])) || (grepl('N$', i))) {
    formattedDescriptives <-
      c(formattedDescriptives,
        x[, i]);
  } else {
    formattedDescriptives <-
      c(formattedDescriptives,
        round(x[, i], digits));
  }
}

tmpDf <-
  data.frame(Labels = paste0(labels[show], " : "),
             Estimates = formattedDescriptives);

ufs::kblXtra(
  tmpDf,
  col.names = NULL,
  align = c("r", "l"),
  row.names = FALSE,
  escape = TRUE
);

```

```{r, echo=echoPartial, results='asis', eval=(!is.null(attr(x, "histogram"))), fig.width=5, fig.height=5, fig.cap=paste0("Histogram for ", varName) }

ufs::heading(chartType, " for ", varName,
             headingLevel = headingLevel+1);

attr(x, "histogram");

```

```{r, echo=echoPartial, results='asis', eval=(singleDescriptives && (!is.null(attr(x, "boxplot")))), fig.width=5, fig.height=5, fig.cap=paste0("Boxplot for ", varName) }

ufs::heading("Boxplot for ", varName,
             headingLevel = headingLevel+1);

attr(x, "boxplot");

```

```{r, echo=echoPartial, results='asis', eval=multipleDescriptives}

### Descriptives for multiple variables

numericResults <-
  unlist(
    lapply(
      x,
      function(descrRes) {
        return("rosettaDescr" %in% class(descrRes));
      }
    )
  );

if (any(numericResults)) {

  res <-
    do.call(
      rbind,
      lapply(
        x[numericResults],
        function(numericDescr)
          return(
            as.data.frame(numericDescr)
          )
      )
    );

  colsToRound <-
    which(
      unlist(
        lapply(
          names(res),
          function(colName) {
            return(
              (!grepl('N$', colName)) &
                is.numeric(res[, colName])
            )
          }
        )
      )
    );

  res[, colsToRound] <-
    round(res[, colsToRound],
          digits);

  ufs::kblXtra(
    res[, show],
    row.names = TRUE,
    escape = TRUE
  );

}

if (any(!numericResults)) {

  for (i in names(x[!numericResults])) {

    if ("freq" %in% class(x[[i]])) {
      ufs::heading("Frequencies for ", i, headingLevel = headingLevel+1);
      ufs::kblXtra(
        x[[i]]$dat,
        row.names = TRUE,
        escape = TRUE
      );
    } else {
      print(x[[i]]);
    }

    cat("\n\n");

  }
}

```



```{r, echo=echoPartial, results='asis', eval=(multipleDescriptives && !is.null(attr(x[[1]], "histogram"))), fig.width=8, fig.height=(2 * ceiling(length(x)/4)), fig.cap=paste0("Histograms for variables in data frame ", attr(x, "datasetName")) }

ufs::heading("Histograms for variables in data frame ", attr(x, "datasetName"),
             headingLevel=headingLevel + 1);

histograms <-
  lapply(names(x),
         function(currentDescr) {
           if (is.null(attr(x[[currentDescr]], "histogram"))) {
             return(ggplot2::ggplot() + ggplot2::theme_void());
           }
           return(
             attr(x[[currentDescr]], "histogram") +
               ggplot2::labs(
                 y = NULL,
                 x = NULL,
                 title = currentDescr
               )
           );
         });
arrangedHistograms <-
  gridExtra::arrangeGrob(
    grobs=histograms,
    ncol=min(maxPlotCols, length(histograms))
  );
grid::grid.draw(arrangedHistograms);

```

```{r, echo=echoPartial, results='asis', eval=(multipleDescriptives && !is.null(attr(x[[1]], "boxplot"))), fig.width=8, fig.height=(2 * ceiling(length(x)/4)), fig.cap=paste0("Boxplots for variables in data frame ", attr(x, "datasetName")) }

ufs::heading("Boxplots for variables in data frame ", attr(x, "datasetName"),
             headingLevel=headingLevel + 1);

boxplots <-
  lapply(names(x),
         function(currentDescr) {
           if (is.null(attr(x[[currentDescr]], "boxplot"))) {
             return(ggplot2::ggplot() + ggplot2::theme_void());
           }
           return(
             attr(x[[currentDescr]], "boxplot") +
               ggplot2::labs(
                 y = NULL,
                 x = NULL,
                 title = currentDescr
               )
           );
         });
arrangedBoxplots <-
  gridExtra::arrangeGrob(
    grobs=boxplots,
    ncol=min(maxPlotCols, length(boxplots))
  );
grid::grid.draw(arrangedBoxplots);

```


```{r echo=FALSE}
if (!is.null(oldKableViewOption)) {
  options(kableExtra_view_html = oldKableViewOption);
}
if (!is.null(oldKnitrKableNAOption)) {
  options(knitr.kable.NA = oldKnitrKableNAOption);
}

```

</div>
<div style="display:block;clear:both;" class="rosetta-descr-end"></div>
