This shiny app generate results from elipots lectures.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

285 lines
13 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. library(shiny)
  2. library(openxlsx)
  3. library(readxl)
  4. # library(ggplot2)
  5. library(reshape2)
  6. # library(dplyr)
  7. library(ggbeeswarm)
  8. library(magrittr)
  9. library(flextable)
  10. source("funcions.R")
  11. library(tidyverse)
  12. library(rstatix)
  13. library(ggpubr)
  14. ui <- fluidPage(
  15. #Navbar
  16. navbarPage("ELISPOTS",
  17. tabPanel("Diseño",
  18. sidebarPanel(
  19. fileInput(inputId = "file1", label = "Dades", multiple = F),
  20. selectInput(inputId = "test", "Test Estadístic", selected = "Ttest", choices = c("T-test (adj Holm)","Wilcoxon (adj Holm)")),
  21. sliderInput(inputId = "umbral_pos", "Mínimo para positivo:", min = 0, max=100, step = 5, value = 10),
  22. checkboxInput(inputId = "positive", label = "Mostrar positivitat", value = F),
  23. checkboxInput(inputId = "showstats", label = "Mostrar estadística", value = F),
  24. downloadButton("downloadData", "Descarregar Informe")
  25. ),
  26. mainPanel(
  27. plotOutput("distPlot"),
  28. uiOutput("flexstats")
  29. )
  30. ),
  31. tabPanel("Exportar",
  32. sidebarPanel(width=2,
  33. sliderInput("width", "Ancho", min=1000, max=20000, step=1000, value=10000),
  34. sliderInput("height", "Altura", min=1000, max=20000, step=1000, value=6000),
  35. textInput("colors", label="Colors", value=""),
  36. sliderInput("boxplot-width", "% Ancho Boxplots", min=0.1, max=1, step=0.1, value=0.7),
  37. sliderInput("point-size", "Tamaño puntos", min=1, max=10, step=1, value=3),
  38. sliderInput("font-size", "Tamaño textos", min=5, max=30, step=1, value=11),
  39. checkboxInput(inputId = "stats2", label = "Mostrar estadística", value = F),
  40. checkboxInput(inputId = "legend", label = "Mostrar llegenda", value = T),
  41. selectInput("theme", "Seleccionar Tema", selected="BW", choices=c("BW", "Default", "Classic")),
  42. downloadButton("downloadPicture", "Exportar")
  43. ),
  44. mainPanel(
  45. uiOutput("expPlotUI")
  46. )
  47. )
  48. )
  49. )
  50. # Define server logic required to draw a histogram
  51. server <- function(input, output) {
  52. dades<-reactiveValues()
  53. dades$taula<-NULL
  54. dades$stats<-NULL
  55. dades$final<-NULL
  56. dades$maps<-NULL
  57. dades$plot<-NULL
  58. observe({
  59. if (!is.null(input$file1)){
  60. dades$taula<-read_xlsx(input$file1$datapath)
  61. }
  62. })
  63. output$distPlot <- renderPlot({
  64. observeEvent(dades$taula, {})
  65. if (!is.null(dades$taula)){
  66. ctrl<-"Ctrl+"
  67. mock<-"Mock"
  68. table<-dades$taula[,colnames(dades$taula) != "Groups"]
  69. t_mean<-dcast(melt(table, id="Mice"),Mice~variable, mean, na.rm=T)
  70. if (length(grep("Mock", colnames(t_mean))) == 1){
  71. t_substr<-data.frame("Mice"=t_mean[,1],
  72. as.data.frame(t(apply(t_mean[,2:ncol(table)], 1, function(x) x-x[mock])))
  73. )
  74. t_mean_group<-merge(t_mean, unique(dades$taula[c("Mice","Groups")]), id="Mice")
  75. t_mean_group$Groups<-as.factor(t_mean_group$Groups)
  76. mock_mean<-dcast(t_mean_group, Groups~., value.var=mock, mean)
  77. mock_mean[,2]<-mock_mean[,2]*2
  78. mock_mean[mock_mean$. < input$umbral_pos,2]<-input$umbral_pos
  79. t_substr<-merge(t_substr, unique(dades$taula[c("Mice","Groups")]), id="Mice")
  80. t_substr<-t_substr[,c(1, ncol(t_substr), 2:(ncol(t_substr)-1))]
  81. t_substr<-t_substr[,c("Mice", "Groups", colnames(t_substr)[!colnames(t_substr) %in% c("Mice", "Groups")])]
  82. t_substr[,3:ncol(t_substr)]<-apply(t_substr[,3:ncol(t_substr)],2, function(x) replace(x, which(x < 0),0))
  83. colnames(t_substr)<-c("Mice", "Groups", colnames(t_mean)[2:ncol(t_mean)])
  84. }else{
  85. t_especifica<-t_mean[,grep("Mock_", colnames(t_mean), invert=T)]
  86. t_mock<-t_mean[,c(which(colnames(t_mean) == "Mice"),grep("Mock_", colnames(t_mean)))]
  87. t_temp<-melt(t_especifica, variable.name = "condition", value.name = "spots")
  88. t_temp["spots_mock"]<-melt(t_mock, variable.name = "condition")[,"value"]
  89. t_substr<-data.frame(t_temp[c("Mice","condition")], "spots"=t_temp["spots"]-t_temp["spots_mock"])
  90. t_substr<-dcast(t_substr, Mice~condition)
  91. t_substr<-merge(t_substr, unique(dades$taula[c("Mice","Groups")]), id="Mice")
  92. t_substr$Groups<-as.factor(t_substr$Groups)
  93. }
  94. t_substr_gp<-t_substr
  95. t_substr_gp[3:ncol(t_substr)]<-apply(t_substr[3:ncol(t_substr)], 2, function(x) gsub(".",",",x, fixed=T))
  96. t_substr_gp<-t_substr_gp[order(factor(t_substr_gp$Mice, levels = unique(table$Mice))),]
  97. doc<-t(t_substr_gp)
  98. write.xlsx(doc, "data4graphpad.xlsx",rowNames=T, overwrite=T)
  99. t<-melt(t_substr[,!colnames(t_substr) %in% c(ctrl, mock)])
  100. if (input$showstats == F){
  101. t_stats<-as.data.frame(matrix(nrow=0, ncol=6))
  102. colnames(t_stats)<-c("variable", "group1", "group2", "p.adj", "p.signif", "Method")
  103. t_maps<-list()
  104. t_maps[["label"]]<-as.data.frame(matrix(nrow = 0, ncol=2))
  105. colnames(t_maps$label)<-c("x", "y")
  106. t_maps[["brackets"]]<-as.data.frame(matrix(nrow = 0, ncol=4))
  107. colnames(t_maps$brackets)<-c("y1", "y2", "x1", "x2")
  108. dades$stats<<-t_stats
  109. dades$maps<<-t_maps
  110. }else{
  111. if (input$test == "T-test (adj Holm)"){
  112. t_stats<-multi_stats(t, "value", "variable", "Groups", stat.test = "ttest")
  113. }
  114. if (input$test == "Wilcoxon (adj Holm)"){
  115. t_stats<-multi_stats(t, "value", "variable", "Groups", stat.test = "wilcox")
  116. }
  117. dades$stats<<-t_stats
  118. t_stats<-t_stats %>% filter(p.signif != "ns")
  119. t_maps<-generate_labstats(t_stats, t, "value", "variable", "Groups")
  120. dades$maps<<-t_maps
  121. }
  122. if (length(unique(dades$taula %>% pull(Groups))) < 2){
  123. dades$stats<<-null
  124. }
  125. c(ctrl, mock)[c(ctrl, mock) %in% colnames(t_substr)]
  126. dades$final<<-t_substr %>% select(-c(ctrl, mock)[c(ctrl, mock) %in% colnames(t_substr)])
  127. set.seed(123)
  128. if (input$positive == T){
  129. ids=c("Mice", "Groups", c(ctrl, mock)[c(ctrl, mock) %in% colnames(t_substr)])
  130. validate(
  131. need(exists("mock_mean"), "No se puede elegir positividad con múltiples mocks")
  132. )
  133. if (exists("mock_mean")){
  134. ggplot(melt(t_substr, id=ids), aes(variable, value))+
  135. labs(x="", y="Spots/2.5*10^5 cells")+
  136. # geom_errorbar(stat="summary", position=position_dodge(width=0.9), width=0.5, aes(fill=Groups))+
  137. geom_hline(data=mock_mean, aes(color=Groups, yintercept = `.`))+
  138. # geom_bar(stat="summary", position="dodge", color="black", aes(fill=Groups))+
  139. geom_boxplot(color="black", aes(fill=Groups), alpha=0.4, outlier.alpha = 0)+
  140. geom_jitter(position=position_jitterdodge(jitter.width = 0.2), shape=21, aes(fill=Groups), size=3)+
  141. # geom_quasirandom(position = position_quasirandom(), shape=21)+
  142. scale_x_discrete(limits=colnames(t_substr)[!colnames(t_substr) %in% c("Mice", "Groups", ctrl, mock)])+
  143. geom_segment(data=t_maps$brackets, aes(x=x1, xend=x2, y=y1, yend=y2), color="black")+
  144. geom_text(data=t_stats, aes(t_maps$label$x, t_maps$label$y, label=p.signif), color="black")+
  145. theme_bw()+
  146. theme(axis.text.x=element_text(angle=45, hjust=1))
  147. }
  148. }else{
  149. ids=c("Mice", "Groups", c(ctrl, mock)[c(ctrl, mock) %in% colnames(t_substr)])
  150. ggplot(melt(t_substr, id=ids), aes(variable, value))+
  151. labs(x="", y="Spots/2.5*10^5 cells")+
  152. # geom_errorbar(stat="summary", position=position_dodge(width=0.9), width=0.5, aes(fill=Groups))+
  153. # geom_bar(stat="summary", position="dodge", color="black", aes(fill=Groups))+
  154. geom_boxplot(color="black", aes(fill=Groups), alpha=0.4, outlier.alpha = 0)+
  155. geom_jitter(position=position_jitterdodge(jitter.width = 0.2), shape=21, aes(fill=Groups), size=3)+
  156. # geom_quasirandom(width=0.2, position=position_dodge(), shape=21)+
  157. scale_x_discrete(limits=colnames(t_substr)[!colnames(t_substr) %in% c("Mice", "Groups", ctrl, mock)])+
  158. geom_segment(data=t_maps$brackets, aes(x=x1, xend=x2, y=y1, yend=y2), color="black")+
  159. geom_text(data=t_stats, aes(t_maps$label$x, t_maps$label$y, label=p.signif), color="black")+
  160. theme_bw()+
  161. theme(axis.text.x=element_text(angle=45, hjust=1))
  162. }
  163. }
  164. })
  165. output$flexstats <- renderUI({
  166. observeEvent(dades$stats, {})
  167. t_stats<-dades$stats
  168. if (!is.null(dades$stats)){
  169. t_stats %>%
  170. flextable() %>%
  171. theme_vanilla() %>%
  172. fontsize(size=14, part="all") %>%
  173. padding(padding=10, part="all") %>%
  174. color(~ p.adj < 0.05, color = "red")%>%
  175. autofit() %>% htmltools_value()
  176. }
  177. })
  178. output$expPlotUI<- renderUI({
  179. if (!is.null(dades$final)){
  180. plotOutput("expPlot", width=paste0(input$width/10,"px"), height = paste0(input$height/10, "px"))
  181. }
  182. })
  183. output$expPlot <- renderPlot({
  184. observeEvent(dades$final, {})
  185. if (!is.null(dades$final)){
  186. print(dades$stats)
  187. t_substr<-dades$final
  188. t_stats<-dades$stats %>% filter(p.signif != "ns")
  189. t_maps<-dades$maps
  190. ids<-c("Mice", "Groups")
  191. set.seed(123)
  192. g<-ggplot(melt(t_substr, id=ids), aes(variable, value))+
  193. labs(x="", y="Spots/2.5*10^5 cells")+
  194. geom_boxplot(color="black", aes(fill=Groups), alpha=0.4, outlier.alpha = 0, position=position_dodge(width=0.8),width=input$`boxplot-width`)+
  195. geom_jitter(position=position_jitterdodge(jitter.width = 0.2), shape=21, aes(fill=Groups), size=input$`point-size`)+
  196. scale_x_discrete(limits=colnames(t_substr)[!colnames(t_substr) %in% c("Mice", "Groups")])
  197. if (input$theme == "BW"){
  198. g<-g+theme_bw(base_size = input$`font-size`)
  199. }
  200. if (input$theme == "Classic"){
  201. g<-g+theme_classic(base_size = input$`font-size`)
  202. }
  203. if (input$theme == "Default"){
  204. g<-g+theme_gray(base_size = input$`font-size`)
  205. }
  206. g<-g+theme(axis.text.x=element_text(angle=45, hjust=1))
  207. if (input$stats2 == T){
  208. g<-g+geom_segment(data=t_maps$brackets, aes(x=x1, xend=x2, y=y1, yend=y2), color="black")+
  209. geom_text(data=t_stats, aes(t_maps$label$x, t_maps$label$y, label=p.signif), color="black")
  210. }
  211. if (input$legend == F){
  212. g<-g+guides(color=FALSE, fill=FALSE)
  213. }
  214. if (input$colors != ""){
  215. v_col<-strsplit(input$colors, ",")[[1]]
  216. g<-g+scale_color_manual(values=v_col)+
  217. scale_fill_manual(values=v_col)
  218. }
  219. dades$plot<<-g
  220. g
  221. }
  222. }, res=72)
  223. output$downloadData <- downloadHandler(
  224. filename = function() {
  225. paste("elispot", ".zip", sep="")
  226. },
  227. content = function(file){
  228. print(file)
  229. # tempReport <- file.path(tempdir(), "elispots.Rmd")
  230. # file.copy("elispots.Rmd", tempReport, overwrite = TRUE)
  231. params=list(file=input$file1$datapath, positive=input$positive, showstats=input$showstats, test=input$test, umbral_pos=input$umbral_pos)
  232. rmarkdown::render("elispots.Rmd", output_file="Results_elispot.html", params=params, envir = new.env(parent = globalenv()))
  233. zip(file,
  234. c("Results_elispot.html","data4graphpad.xlsx")
  235. )
  236. },
  237. contentType="application/zip"
  238. )
  239. output$downloadPicture <- downloadHandler(
  240. filename = function() {
  241. paste("Figura", ".zip", sep="")
  242. },
  243. content = function(file){
  244. print(file)
  245. # tempReport <- file.path(tempdir(), "elispots.Rmd")
  246. # file.copy("elispots.Rmd", tempReport, overwrite = TRUE)
  247. png("plot.png", width = input$width, height=input$height, units = "px", res=720)
  248. plot(dades$plot)
  249. dev.off()
  250. elispot.plot<-dades$plot
  251. save(elispot.plot, file="plot.RObject")
  252. zip(file,
  253. c("plot.png", "plot.RObject")
  254. )
  255. }
  256. )
  257. }
  258. # Run the application
  259. shinyApp(ui = ui, server = server)