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.

286 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
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<-t %>% rename("Condition"="variable") %>% group_by(Condition) %>% t_test(value~Groups)
  113. }
  114. if (input$test == "Wilcoxon (adj Holm)"){
  115. t_stats<-t %>% rename("Condition"="variable") %>% group_by(Condition) %>% wilcox_test(value~Groups)
  116. }
  117. dades$stats<<-t_stats
  118. }
  119. if (length(unique(dades$taula %>% pull(Groups))) < 2){
  120. dades$stats<<-null
  121. }
  122. c(ctrl, mock)[c(ctrl, mock) %in% colnames(t_substr)]
  123. dades$final<<-t_substr %>% select(-c(ctrl, mock)[c(ctrl, mock) %in% colnames(t_substr)])
  124. set.seed(123)
  125. if (input$positive == T){
  126. ids=c("Mice", "Groups", c(ctrl, mock)[c(ctrl, mock) %in% colnames(t_substr)])
  127. validate(
  128. need(exists("mock_mean"), "No se puede elegir positividad con múltiples mocks")
  129. )
  130. if (exists("mock_mean")){
  131. g<-ggplot(melt(t_substr, id=ids), aes(variable, value))+
  132. labs(x="", y="Spots/2.5*10^5 cells")+
  133. # geom_errorbar(stat="summary", position=position_dodge(width=0.9), width=0.5, aes(fill=Groups))+
  134. geom_hline(data=mock_mean, aes(color=Groups, yintercept = `.`))+
  135. # geom_bar(stat="summary", position="dodge", color="black", aes(fill=Groups))+
  136. geom_boxplot(color="black", aes(fill=Groups), alpha=0.4, outlier.alpha = 0)+
  137. geom_jitter(position=position_jitterdodge(jitter.width = 0.2), shape=21, aes(fill=Groups), size=3)+
  138. # geom_quasirandom(position = position_quasirandom(), shape=21)+
  139. scale_x_discrete(limits=colnames(t_substr)[!colnames(t_substr) %in% c("Mice", "Groups", ctrl, mock)])+
  140. geom_segment(data=t_maps$brackets, aes(x=x1, xend=x2, y=y1, yend=y2), color="black")+
  141. geom_text(data=t_stats, aes(t_maps$label$x, t_maps$label$y, label=p.signif), color="black")+
  142. theme_bw()+
  143. theme(axis.text.x=element_text(angle=45, hjust=1))
  144. }
  145. }else{
  146. ids=c("Mice", "Groups", c(ctrl, mock)[c(ctrl, mock) %in% colnames(t_substr)])
  147. g<-ggplot(melt(t_substr, id=ids, variable.name = "Condition"), aes(Condition, value))+
  148. labs(x="", y="Spots/2.5*10^5 cells")+
  149. # geom_errorbar(stat="summary", position=position_dodge(width=0.9), width=0.5, aes(fill=Groups))+
  150. # geom_bar(stat="summary", position="dodge", color="black", aes(fill=Groups))+
  151. geom_boxplot(color="black", aes(fill=Groups), alpha=0.4, outlier.alpha = 0)+
  152. geom_jitter(position=position_jitterdodge(jitter.width = 0.2), shape=21, aes(fill=Groups), size=3)+
  153. # geom_quasirandom(width=0.2, position=position_dodge(), shape=21)+
  154. scale_x_discrete(limits=colnames(t_substr)[!colnames(t_substr) %in% c("Mice", "Groups", ctrl, mock)])+
  155. # geom_segment(data=t_maps$brackets, aes(x=x1, xend=x2, y=y1, yend=y2), color="black")+
  156. # geom_text(data=t_stats, aes(t_maps$label$x, t_maps$label$y, label=p.signif), color="black")+
  157. theme_bw()+
  158. theme(axis.text.x=element_text(angle=45, hjust=1))
  159. }
  160. if (input$showstats == T){
  161. stat.pos<-t_stats %>% add_xy_position(x="Condition", step.increase = 0.06, dodge = 0.75)
  162. g+stat_pvalue_manual(stat.pos,hide.ns = T)
  163. }else{
  164. g
  165. }
  166. }
  167. })
  168. output$flexstats <- renderUI({
  169. observeEvent(dades$stats, {})
  170. t_stats<-dades$stats
  171. if (!is.null(dades$stats)){
  172. t_stats %>%
  173. flextable() %>%
  174. theme_vanilla() %>%
  175. fontsize(size=14, part="all") %>%
  176. padding(padding=10, part="all") %>%
  177. color(~ p.adj < 0.05, color = "red")%>%
  178. autofit() %>% htmltools_value()
  179. }
  180. })
  181. output$expPlotUI<- renderUI({
  182. if (!is.null(dades$final)){
  183. plotOutput("expPlot", width=paste0(input$width/10,"px"), height = paste0(input$height/10, "px"))
  184. }
  185. })
  186. output$expPlot <- renderPlot({
  187. observeEvent(dades$final, {})
  188. if (!is.null(dades$final)){
  189. print(dades$stats)
  190. t_substr<-dades$final
  191. t_stats<-dades$stats
  192. ids<-c("Mice", "Groups")
  193. set.seed(123)
  194. g<-ggplot(melt(t_substr, id=ids, variable.name="Condition"), aes(Condition, value))+
  195. labs(x="", y="Spots/2.5*10^5 cells")+
  196. geom_boxplot(color="black", aes(fill=Groups), alpha=0.4, outlier.alpha = 0, position=position_dodge(width=0.8),width=input$`boxplot-width`)+
  197. geom_jitter(position=position_jitterdodge(jitter.width = 0.2), shape=21, aes(fill=Groups), size=input$`point-size`)+
  198. scale_x_discrete(limits=colnames(t_substr)[!colnames(t_substr) %in% c("Mice", "Groups")])
  199. if (input$theme == "BW"){
  200. g<-g+theme_bw(base_size = input$`font-size`)
  201. }
  202. if (input$theme == "Classic"){
  203. g<-g+theme_classic(base_size = input$`font-size`)
  204. }
  205. if (input$theme == "Default"){
  206. g<-g+theme_gray(base_size = input$`font-size`)
  207. }
  208. g<-g+theme(axis.text.x=element_text(angle=45, hjust=1))
  209. if (input$legend == F){
  210. g<-g+guides(color=FALSE, fill=FALSE)
  211. }
  212. if (input$stats2 == T){
  213. stat.pos<-dades$stats %>% add_xy_position(x="Condition", step.increase = 0.06, dodge = 0.75)
  214. g<-g+stat_pvalue_manual(stat.pos,hide.ns = T)
  215. }
  216. if (input$colors != ""){
  217. v_col<-strsplit(input$colors, ",")[[1]]
  218. g<-g+scale_color_manual(values=v_col)+
  219. scale_fill_manual(values=v_col)
  220. }
  221. dades$plot<<-g
  222. g
  223. }
  224. }, res=72)
  225. output$downloadData <- downloadHandler(
  226. filename = function() {
  227. paste("elispot", ".zip", sep="")
  228. },
  229. content = function(file){
  230. print(file)
  231. # tempReport <- file.path(tempdir(), "elispots.Rmd")
  232. # file.copy("elispots.Rmd", tempReport, overwrite = TRUE)
  233. params=list(file=input$file1$datapath, positive=input$positive, showstats=input$showstats, test=input$test, umbral_pos=input$umbral_pos)
  234. rmarkdown::render("elispots.Rmd", output_file="Results_elispot.html", params=params, envir = new.env(parent = globalenv()))
  235. zip(file,
  236. c("Results_elispot.html","data4graphpad.xlsx")
  237. )
  238. },
  239. contentType="application/zip"
  240. )
  241. output$downloadPicture <- downloadHandler(
  242. filename = function() {
  243. paste("Figura", ".zip", sep="")
  244. },
  245. content = function(file){
  246. print(file)
  247. # tempReport <- file.path(tempdir(), "elispots.Rmd")
  248. # file.copy("elispots.Rmd", tempReport, overwrite = TRUE)
  249. png("plot.png", width = input$width, height=input$height, units = "px", res=720)
  250. plot(dades$plot)
  251. dev.off()
  252. elispot.plot<-dades$plot
  253. save(elispot.plot, file="plot.RObject")
  254. zip(file,
  255. c("plot.png", "plot.RObject")
  256. )
  257. }
  258. )
  259. }
  260. # Run the application
  261. shinyApp(ui = ui, server = server)