```{r, include = FALSE} 
# Load necessary packages
require(ggplot2)
require(knitr)
require(clusterProfiler)
```


```{r table_top_genes, echo = FALSE, results = 'asis'}
DEG_cols <- grep("_DEG$", names(DEGH_results), value=TRUE)
FC_cols <- grep("^logFC", names(DEGH_results), value=TRUE)

top_bot_genes_list <- lapply(DEG_cols, function(DEG_col) {
	method_name <- strsplit(DEG_col, "_")[[1]][1]
	FC_col <- paste("logFC", method_name, sep="_")
	DEGH_results_method <- DEGH_results[DEGH_results[,DEG_col] == TRUE,]
	FCs <- DEGH_results_method[, FC_col]

	ordered_FC_vals <- order(DEGH_results_method[, FC_col])
	index_bottom_15 <- intersect(head(ordered_FC_vals, 15), which(FCs<0))
	index_top_15 <- intersect(tail(ordered_FC_vals, 15), which(FCs>0))
	top_15_IDs <- row.names(DEGH_results_method[index_top_15, ])
	bot_15_IDs <- row.names(DEGH_results_method[index_bottom_15, ])
	return(list(top_15_IDs, bot_15_IDs))
})

all_top_IDs <- unique(unlist(sapply(top_bot_genes_list, "[", 1)))
all_bot_IDs <- unique(unlist(sapply(top_bot_genes_list, "[", 2)))
topgenes <- DEGH_results[all_top_IDs, c("input_IDs", FC_cols, "mean_logFCs", "SYMBOL")]
botgenes <- DEGH_results[all_bot_IDs, c("input_IDs", FC_cols, "mean_logFCs", "SYMBOL")]

if(exists("annot_table")) {
    if(!is.null(annot_table)) {
	    topgenes$original_ids <- row.names(topgenes)
	    botgenes$original_ids <- row.names(botgenes)
    }
}

# Message
cat("## **Top genes**\n")
cat(paste(c("Table of signifcant genes. Variables taken into account are being shown into table (except gene symbols/ID). Top of positive (",nrow(topgenes)," items) and negative (",nrow(botgenes)," items) are being shown in two different tables\n"), collapse = ""))
```

```{r render_topgenes, echo = FALSE, results = 'asis'}
cat("\n### **Top positive**\n")
# Render
DT::datatable(topgenes, filter = 'top', rownames = FALSE, extensions = c('Buttons','ColReorder'),
                    options = list(
                    	colReorder = TRUE,
                    	dom = 'lftBip',
                        buttons = c('copy', 'csv', 'excel')
                    ))
```
```{r render_botgenes, echo = FALSE, results = 'asis'}
cat("\n### **Top negative**\n")
# Render
DT::datatable(botgenes, filter = 'top', rownames = FALSE, extensions = c('Buttons','ColReorder'),
                    options = list(
                    	colReorder = TRUE,
                    	dom = 'lftBip',
                        buttons = c('copy', 'csv', 'excel')
                    ))

```

