| library(shiny) | |
| # library(ggplot2) | |
| library(reshape2) | |
| library(openxlsx) | |
| # library(dplyr) | |
| library(car) | |
| library(ggbeeswarm) | |
| library(gtools) | |
| library(gridExtra) | |
| source("../../funcions.R") | |
| library(survminer) | |
| library(survival) | |
| library(plotrix) | |
| library(tidyverse) | |
| library(ggpubr) | |
| library(rstatix) | |
| 
 | |
| # Define UI for application | |
| ui <- fluidPage( | |
|     | |
|    #Navbar | |
|    navbarPage("Seguimiento in vivos", | |
|               tabPanel("Diseño", | |
|                 sidebarPanel( | |
|                   fileInput(inputId = "file_sizes", label = "Hoja de tamaños", multiple = F), | |
|                   selectInput(inputId = "measure_sys", "Sistema de medida", selected = "L-W-D", choices = c("L-W-D","Min-Max","Absorbance")), | |
|                   uiOutput('ncages'), | |
|                   uiOutput('lowcut'), | |
|                   uiOutput('upcut'), | |
|                   uiOutput('goButton'), | |
|                   uiOutput('iterations'), | |
|                   downloadButton("downloadData", "Descargar Excel") | |
|                   ), | |
|                 mainPanel( | |
|                   plotOutput("firstPlot"), | |
|                   plotOutput("distPlot"), | |
|                   tableOutput("distTable") | |
|                 ) | |
|               ), | |
|               tabPanel("Análisis", | |
|                        sidebarPanel( | |
|                          fileInput(inputId = "file_analy", label = "Hoja de análisis", multiple = F), | |
|                          selectInput(inputId = "vacc", "Experimento de Vacunación", selected = "No", choices = c("Sí","No")), | |
|                          uiOutput('cutoffUI'), | |
|                          checkboxInput("filter_stats","Filtrar Estadística"), | |
|                          downloadButton("downloadVolume", "Descargar Volúmenes") | |
|                        ), | |
|                        mainPanel( | |
|                          h3('Ratones'), | |
|                          tableOutput('ntable'), | |
|                          h3('Cinéticas'), | |
|                          plotOutput('cin_group'), | |
|                          plotOutput('cin_indiv'), | |
|                          plotOutput('survival', height="800px"), | |
|                          h3('Estadística'), | |
|                          verbatimTextOutput('stats'), | |
|                          tableOutput('tab_stats') | |
|                        )), | |
|               tabPanel("Exportar", | |
|                        sidebarPanel(width=2, | |
|                                     h3('Seleccionar figura'), | |
|                                     selectInput("fig_id", "", selected="", choices=c("Cinética Grupo", "Cinética Individual", "Survival")), | |
|                                     h3('Formato'), | |
|                                     sliderInput("width", "Ancho", min=1000, max=20000, step=1000, value=10000), | |
|                                     sliderInput("height", "Altura", min=1000, max=20000, step=1000, value=6000), | |
|                                     textInput("colors", label="Colors", value=""), | |
|                                     sliderInput("errorbar-width", "% Ancho errorbars", min=0.05, max=1, step=0.05, value=0.05), | |
|                                     sliderInput("point-size", "Tamaño puntos", min=1, max=10, step=1, value=3), | |
|                                     sliderInput("font-size", "Tamaño textos", min=5, max=30, step=1, value=11), | |
|                                     checkboxInput(inputId = "logscale", label="Escala logarítmica eje Y", value=F), | |
|                                     checkboxInput(inputId = "legend", label = "Mostrar llegenda", value = T), | |
|                                     selectInput("theme", "Seleccionar Tema", selected="BW", choices=c("BW", "Default", "Classic")), | |
|                                     downloadButton("downloadPicture", "Exportar") | |
|                        ), | |
|                        mainPanel( | |
|                          uiOutput("expPlotUI") | |
|                        ) | |
|               ) | |
|               ) | |
|     | |
|    ) | |
| 
 | |
| # Define server logic required to draw a histogram | |
| server <- function(input, output) { | |
|    | |
|   # Diseño | |
|   dades<-reactiveValues() | |
|   dades$taula<-NULL | |
|   dades$groups<-NULL | |
|   dades$db<-NULL | |
|   observe({ | |
|     if (!is.null(input$file_sizes)){  | |
|       taula<-read.xlsx(input$file_sizes$datapath, sheet = 1, sep.names = " ") | |
|       if ("DPV" %in% colnames(taula)){ | |
|         taula<-dcast(taula, Cage+`ID animal`+`ID tumor`+Group~DPV, value.var = "0") | |
|         # taula$Major<-taula$Major/1000 | |
|         # taula$Minor<-taula$Minor/1000 | |
|         # taula["Volume"]<-((taula$Major*taula$Minor*taula$Minor)*(pi/6))*1000 | |
|         taula$Major<-taula$Major | |
|         taula$Minor<-taula$Minor | |
|         taula["Volume"]<-((taula$Major*taula$Minor*taula$Minor)*(pi/6)) | |
|       } | |
|       dades$taula<-taula | |
|       dades$groups<-read.xlsx(input$file_sizes$datapath, sheet = 2)[,1] | |
|     } | |
|   }) | |
|   output$firstPlot <- renderPlot({ | |
|     observeEvent(dades$taula, {}) | |
|     if (!is.null(dades$taula)){ | |
|       ggplot(dades$taula, aes(x="1", y=Volume))+geom_hline(yintercept = c(input$lowcut, input$upcut), color="red")+geom_quasirandom(width=0.2) | |
|     } | |
|   }) | |
|    | |
|   output$iterations<-renderUI({ | |
|     if (!is.null(dades$taula)){ | |
|       sliderInput("iterations", "Iteraciones", min=100, max=2000, step=100, value=100)  | |
|     } | |
|   }) | |
|   output$lowcut<-renderUI({ | |
|     if (!is.null(dades$taula)){ | |
|       cut.max<-round(max(dades$taula$Volume, na.rm = T), 2) | |
|       step<-round(max(dades$taula$Volume, na.rm = T)/20, 2) | |
|       sliderInput("lowcut", "Corte inferior", min=0, max=cut.max, step=step, value=0) | |
|     } | |
|   }) | |
|   output$upcut<-renderUI({ | |
|     if (!is.null(dades$taula)){ | |
|       cut.max<-round(max(dades$taula$Volume, na.rm = T), 2)+0.01 | |
|       step<-round(max(dades$taula$Volume, na.rm = T)/20, 2) | |
|       sliderInput("upcut", "Corte superior", min=0, max=cut.max, step=step, value=cut.max) | |
|     } | |
|   }) | |
|   output$goButton<-renderUI({ | |
|     if (!is.null(dades$taula)){ | |
|       actionButton("goButton", "Selecciona") | |
|     } | |
|   }) | |
|   output$ncages<-renderUI({ | |
|     if (is.null(dades$taula)){ | |
|       sliderInput("ncages", "Cajas", min=1, max=10, value=1) | |
|     } | |
|   }) | |
|   grafic<-eventReactive(input$goButton,{ | |
|     df<-dades$taula | |
|     df<-df[!is.na(df$Volume),] | |
|     up_cuttof<-input$upcut | |
|     low_cuttof<-input$lowcut | |
|     print(up_cuttof) | |
|     df<-df[df$Volume < up_cuttof & df$Volume >= low_cuttof,] | |
|      | |
|      | |
|     # df["Mouse"]<-gsub("[a-zA-Z]", "", df$MouseID) | |
|     print(df$Volume) | |
|     s<-shapiro.test(df$Volume)[[2]] | |
|      | |
|     ngroup<-length(dades$groups) | |
|     ind.list<-list() | |
|     pval.list<-list() | |
|     lvn.list<-list() | |
|     test.list<-list() | |
|     for (data in 1:input$iterations){ | |
|       interr=T | |
|       while(interr == T){ | |
|         ind<-sample(rep(dades$groups, each=ceiling(length(unique(df$`ID animal`))/ngroup)), length(unique(df$`ID animal`))) | |
|         df_temp<-merge(df[,c("ID animal", "ID tumor","Volume")], data.frame("ID animal"=unique(df$`ID animal`), "group"=as.factor(ind),check.names=F)) | |
|         if ((nrow(df_temp)/ngroup) %% 2 == 0){ | |
|           interr<-any(table(df_temp$group) < floor(nrow(df_temp)/ngroup) | table(df_temp$group) > ceiling(nrow(df_temp)/ngroup))   | |
|         }else{ | |
|           # interr<-any(table(df_temp$group) < (floor(nrow(df_temp)/ngroup)-1) | table(df_temp$group) > (ceiling(nrow(df_temp)/ngroup)+1)) | |
|           interr<-diff(range(table(ind))) > 1 | |
|         } | |
|       } | |
|       ind.list[[data]]<-df_temp[,c("ID animal", "ID tumor","group","Volume")] | |
|       lvn.list[data]<-leveneTest(Volume ~ group, data = df_temp[,3:4])[[2]][1] | |
|       if (s < 0.05){ | |
|         k<-kruskal.test(df_temp$Volume,df_temp$group) | |
|         test.list[data]<-k[[1]][1] | |
|         pval.list[data]<-k[[3]][1] | |
|       }else{ | |
|         res.aov<-aov(Volume~group, data=df_temp) | |
|         pval.list[data]<-summary(res.aov)[[1]][[5]][1] | |
|         test.list[data]<-summary(res.aov)[[1]][[4]][1] | |
|       } | |
|     } | |
|     index<-which(unlist(lvn.list) == min(unlist(lvn.list)[which(unlist(pval.list) %in% sort(unlist(pval.list), decreasing = T)[1:20])])) | |
|     df_def<-merge(df, ind.list[[index]]) | |
|     if ("Group" %in% colnames(df_def)){ | |
|       df_def<-df_def %>% select(-"Group")  | |
|     } | |
|     df_def<-merge(dades$taula %>% select(-Group), df_def[,c("ID animal", "group")] %>% unique, all=T, by="ID animal") %>% select(c(`ID animal`, `ID tumor`, Volume, Cage, Major, Minor, group)) | |
|     df_def[!paste0(df_def$`ID animal`, df_def$`ID tumor`) %in% paste0(df$`ID animal`, df$`ID tumor`),"group"]<-NA | |
|     dades$db<-df_def | |
| 
 | |
|      | |
|     ggplot(df_def, aes(group, Volume))+ | |
|       geom_boxplot(outlier.alpha = F)+ | |
|       geom_jitter(width=0.25)+ | |
|       geom_point(stat="summary", color="blue", size=3) | |
|       # lims(y=c(0,max(df_def$Volume)+10)) | |
|   }) | |
|   output$distPlot <- renderPlot({ | |
|     observeEvent(dades$taula, {}) | |
|     if (!is.null(dades$taula)){ | |
|       grafic() | |
|     } | |
|   }) | |
|    | |
|   output$distTable <- renderTable({ | |
|     observeEvent(dades$db, {}) | |
|     if (!is.null(dades$db)){ | |
|       df<-dades$db | |
|       df_sum<-dcast(df, group~., value.var = "Volume", fun.aggregate = mean, na.rm=T) %>% rename("Mean"=".") | |
|       df_sum["SEM"]<-dcast(df, group~., value.var = "Volume", fun.aggregate = std.error, na.rm=T) %>% pull(`.`) | |
|       df_sum | |
|     } | |
|   }) | |
|    | |
|   output$downloadData <- downloadHandler( | |
|      | |
|     filename = function() { | |
|       paste("invivo", ".xlsx", sep="") | |
|     }, | |
|     content = function(file){ | |
|       ncages<-input$ncages | |
|       nrat_cage<-5 | |
|       id_tumors<-c("L","R") | |
|       timepoint<-c(7,10,13,16,19,22,25) | |
|        | |
|       if (!is.null(input$file_sizes)){ | |
|         dtemplate<-dades$db %>% select(-Volume) | |
|         dtemplate<-melt(dtemplate, id=c("Cage", "ID animal", "ID tumor", "group"), variable.name = "DPV", value.name = "0") %>% rename("Group"="group") | |
|         dtemplate<-dtemplate[,c("Cage", "ID animal", "ID tumor", "Group", "DPV", "0")] %>% arrange(`ID animal`, `ID tumor`) | |
|         # template<-expand.grid(dades$db$MouseID, timepoint) | |
|         # colnames(template)<-c("MouseID", "Timepoint") | |
|         # template<-template[order(template$Timepoint, template$MouseID),] | |
|         # template<-merge(template, dades$db[c("MouseID", "group")]) | |
|         # if (input$measure_sys == "L-W-D"){ | |
|         #   template<-rbind(template, template, template) | |
|         #   template<-template[order(template$Timepoint, template$MouseID),] | |
|         #   template["TS"]<-rep(c("TS-Length", "TS-Width", "TS-Deep"), nrow(template)/3) | |
|         #   dtemplate<-dcast(template, MouseID+group+TS~Timepoint)  | |
|         #   dtemplate<-dtemplate[mixedorder(as.character(dtemplate$MouseID)),] | |
|         # } | |
|         # if (input$measure_sys == "Min-Max"){ | |
|         #   template<-rbind(template, template) | |
|         #   template<-template[order(template$Timepoint, template$MouseID),] | |
|         #   template["DPV"]<-rep(c("Major", "Minor"), nrow(template)/2) | |
|         #   dtemplate<-dcast(template, MouseID+group+DPV~Timepoint) | |
|         #   dtemplate<-dtemplate[mixedorder(as.character(dtemplate$MouseID)),] | |
|         # } | |
|         # dtemplate<-dtemplate %>% add_column(.after="MouseID", "ID tumor"=dtemplate$MouseID)%>% rename(`ID animal`=MouseID) | |
|         # dtemplate["ID tumor"]<-gsub("[[:digit:]]","",dtemplate$`ID tumor`) | |
|         # dtemplate["ID animal"]<-gsub("[LR]","",dtemplate$`ID animal`) | |
|         # dtemplate[,5:ncol(dtemplate)]<-"" | |
|       }else{ | |
|         template<-expand.grid(LETTERS[1:ncages], 1:5, id_tumors, timepoint)[,-2] | |
|         colnames(template)<-c("Cage", "ID tumor", "Timepoint") | |
|         nids<-length(id_tumors)*length(timepoint) | |
|         template[order(template$Cage),"ID animal"]<-rep(1:(nrow(template)/(nids)), each=nids) | |
|         template<-template[order(template$Timepoint, template$Cage, template$`ID animal`),] | |
|         template["Group"]<-"" | |
|         if (input$measure_sys == "L-W-D"){ | |
|           template<-rbind(template, template, template) | |
|           template<-template[order(template$Timepoint, template$Cage, template$`ID animal`, template$`ID tumor`),] | |
|           template["TS"]<-rep(c("TS-Length", "TS-Width", "TS-Deep"), nrow(template)/3) | |
|           dtemplate<-dcast(template, Cage+`ID animal`+`ID tumor`+Group+TS~Timepoint)  | |
|           dtemplate<-dtemplate[order(match(dtemplate$TS, c("TS-Length", "TS-Width", "TS-Deep"))),] | |
|           dtemplate<-dtemplate[mixedorder(dtemplate$`ID tumor`),] | |
|           dtemplate<-dtemplate[mixedorder(dtemplate$`ID animal`),] | |
|         } | |
|         if (input$measure_sys == "Min-Max"){ | |
|           template<-rbind(template, template) | |
|           template<-template[order(template$Timepoint, template$Cage, template$`ID animal`, template$`ID tumor`),] | |
|           template["DPV"]<-rep(c("Major", "Minor"), nrow(template)/2) | |
|           dtemplate<-dcast(template, Cage+`ID animal`+`ID tumor`+Group+DPV~Timepoint) | |
|         } | |
|         dtemplate[,6:ncol(dtemplate)]<-"" | |
|       } | |
|       write.xlsx(dtemplate,file) | |
|     } | |
|   ) | |
|    | |
|   # Análisis | |
|   analysis<-reactiveValues() | |
|   analysis$taula<-NULL | |
|   analysis$taula_def<-NULL | |
|   analysis$taula_vol<-NULL | |
|   observe({ | |
|     if (!is.null(input$file_analy)){  | |
|       analysis$taula<-read.xlsx(input$file_analy$datapath, sheet = 1, check.names = F, sep.names = " ") | |
|     } | |
|   }) | |
|   output$cutoffUI<-renderUI({ | |
|     if (!is.null(analysis$taula_def)){ | |
|       observeEvent(analysis$taula_def, {}) | |
|       max_val<-max(analysis$taula_def$Volume, na.rm = T) | |
|       print(max_val) | |
|       sliderInput("cutoff", "Cutoff para Survival", min=0, max=round(max_val), step=round(max_val)/200, value=max_val) | |
|     } | |
|   }) | |
|   output$ntable<-renderTable({ | |
|     if (!is.null(input$file_analy)){ | |
|       observeEvent(analysis$taula, {}) | |
|       stattest<-"dunn" | |
|       oneside<-"" | |
| 
 | |
|       table<-analysis$taula | |
|       if ("ID.animal" %in% colnames(table)){table<-rename(table, "ID animal"=`ID.animal`)} | |
|       if ("ID" %in% colnames(table)){table<-rename(table, "ID animal"=ID)} | |
|       if ("ID.tumor" %in% colnames(table)){table<-rename(table, "ID tumor"=`ID.tumor`)} | |
|       # table[table$ID.tumor == "R","0"]<-NA | |
|       col_nodays<-c("ID","Code", "Cage","Group", "ID.animal","ID animal", "ID.tumor", "ID tumor", "TS","DPV", "Absorbance") | |
|       if (length(grep(0, colnames(table)[!colnames(table) %in% col_nodays])) == 0){ | |
|         table["0"]<-0 | |
|       } | |
|       table<-melt(table, id=colnames(table)[colnames(table) %in% col_nodays], variable.name = "Timepoint") | |
|       table$Timepoint<-gsub("[A-Za-z ]","",table$Timepoint) | |
|       print(table) | |
|       if ("DPV" %in% colnames(table)){ | |
|         table<-dcast(table, Cage+`ID animal`+`ID tumor`+Group+Timepoint~DPV, value.var = "value") | |
|         table$Major<-table$Major | |
|         table$Minor<-table$Minor | |
|         table["Volume"]<-((table$Major*table$Minor*table$Minor)*(pi/6)) | |
|       } | |
|       if ("TS" %in% colnames(table)){ | |
|         table<-dcast(table, Cage+`ID animal`+`ID tumor`+Group+Timepoint~TS, value.var = "value") | |
|         table["Volume"]<-table$`TS-Deep`*table$`TS-Length`*table$`TS-Width`*pi/6 | |
|       } | |
|       if (!"Volume" %in% colnames(table)){table<-rename(table, "Volume"=value)} | |
|       table<-table %>% filter(!is.na(Group)) | |
|       table$Timepoint<-factor(table$Timepoint, levels=mixedsort(as.numeric(as.character(unique(table$Timepoint))))) | |
|       analysis$taula_def<-table | |
|       analysis$taula_vol<-dcast(table, Cage+`ID animal`+`ID tumor`~Timepoint,value.var = "Volume") | |
|       table_plot<-dcast(dcast(table %>% filter(!is.na(Volume)), `ID animal`+Group+Timepoint~., value.var = "Volume", fun.aggregate = mean), Group~Timepoint) | |
|       table_plot | |
|     } | |
|   }) | |
|   output$cin_group<-renderPlot({ | |
|     if (!is.null(input$file_analy) & !is.null(analysis$taula_def)){ | |
|       observeEvent(analysis$taula_def, {}) | |
|       table<-analysis$taula_def | |
|       if (input$vacc == "Sí"){ | |
|         ggplot(table, aes(as.numeric(as.character(Timepoint)), Volume, color=Group, group=Group))+ | |
|           geom_errorbar(stat="summary", width=0.05)+ | |
|           geom_line(stat="summary")+ | |
|           geom_point(stat="summary")+ | |
|           facet_grid(factor(`ID tumor`, labels = c("Vaccination", "Rechallenge"))~., scale="free_y")+ | |
|           labs(x="Days after tumor challenge")+ | |
|           scale_y_continuous(expand = expansion(mult = c(0,0.05)))+ | |
|           scale_x_continuous(expand = expansion(mult = c(0,0.05)), limits = c(0, (round(max(as.numeric(as.character(table$Timepoint))) / 5)+1)*5))+ | |
|           theme_bw()   | |
|       }else{ | |
|         ggplot(table, aes(Timepoint, Volume, color=Group, group=Group))+ | |
|           geom_errorbar(stat="summary",width=0.05)+ | |
|           geom_line(stat="summary")+ | |
|           geom_point(stat="summary")+ | |
|           labs(x="Days after tumor challenge")+ | |
|           scale_y_continuous(expand = expansion(mult = c(0,0.05)))+ | |
|           theme_bw()+ | |
|           theme(axis.text.x=element_text(angle=45, hjust=1)) | |
|       } | |
|        | |
|     } | |
|   }) | |
|   output$cin_indiv<-renderPlot({ | |
|     if (!is.null(input$file_analy) & !is.null(analysis$taula_def)){ | |
|       observeEvent(analysis$taula_def, {}) | |
|       table<-analysis$taula_def | |
|       print(table , ) | |
|       if (input$vacc == "Sí"){ | |
|         ggplot(table, aes(as.numeric(as.character(Timepoint)), Volume, color=Group, group=`ID animal`))+ | |
|           # geom_errorbar(stat="summary", width=0.05)+ | |
|           geom_line()+ | |
|           geom_point()+ | |
|           scale_y_continuous(expand = expansion(mult = c(0,0.05)))+ | |
|           scale_x_continuous(expand = expansion(mult = c(0,0.05)), limits = c(0, (round(max(as.numeric(as.character(table$Timepoint))) / 5)+1)*5))+ | |
|           facet_grid(factor(`ID tumor`, labels = c("Vaccination", "Rechallenge"))~Group, scale="free_y")+ | |
|           labs(x="Days after tumor challenge")+ | |
|           theme_bw()   | |
|       }else{ | |
|         ggplot(table, aes(Timepoint, Volume, color=Group, group=`ID animal`))+ | |
|           # geom_errorbar(stat="summary", width=0.05)+ | |
|           geom_line()+ | |
|           geom_point()+ | |
|           scale_y_continuous(expand = expansion(mult = c(0,0.05)))+ | |
|           # scale_x_continuous(expand = expansion(mult = c(0,0.05)), limits = c(0, (round(max(as.numeric(as.character(table$Timepoint))) / 5)+1)*5))+ | |
|           facet_wrap(.~Group)+ | |
|           labs(x="Days after tumor challenge")+ | |
|           theme_bw()+ | |
|           theme(axis.text.x=element_text(angle=45, hjust=1)) | |
|       } | |
|     } | |
|   }) | |
|    | |
|   output$survival<-renderPlot({ | |
|     if (!is.null(input$file_analy) & !is.null(analysis$taula_def)){ | |
|       observeEvent(analysis$taula_def, {}) | |
|       table<-analysis$taula_def | |
|       if (input$vacc == "Sí"){ | |
|         g<-list() | |
|         for (side in c("L","R")){ | |
|           tableR<-filter(table, `ID tumor` == side) %>% filter(!is.na(Volume)) | |
|           endtime<-dcast(tableR %>% filter(Volume < input$cutoff), Cage+`ID animal`+`ID tumor`+Group~., value.var = "Timepoint", fun.aggregate = function(x){max(as.numeric(as.character(x)))}) %>% rename("end"=".") | |
|           endtime["Dead"]<-dcast(tableR, Cage+`ID animal`+`ID tumor`+Group~., value.var = "Volume", fun.aggregate = function(x){max(as.numeric(as.character(x)))}) %>% pull(".") > input$cutoff | |
|           table_tumor<<-endtime | |
|            | |
|           g[side]<-ggsurvplot(survfit(Surv(table_tumor$end, table_tumor$Dead) ~ table_tumor$Group, data=table_tumor), | |
|                               pval = T, pval.method = T, | |
|                               title = side, | |
|                               # legend.labs = paste(c("< median", ">= median"), "MICA"), | |
|                               ggtheme=theme_classic(base_size=15) | |
|                               # conf.int = TRUE, | |
|                               # Add risk table | |
|                               # risk.table = TRUE, | |
|                               # tables.height = 0.2, | |
|                               # tables.theme = theme_cleantable(), | |
|                                | |
|                               # Color palettes. Use custom color: c("#E7B800", "#2E9FDF"), | |
|                               # or brewer color (e.g.: "Dark2"), or ggsci color (e.g.: "jco") | |
|                               # palette = c("#E7B800", "#2E9FDF") | |
|           ) | |
|         } | |
|         do.call(grid.arrange, g) | |
|          | |
|       }else{ | |
|         tableR<-table %>% filter(!is.na(Volume)) | |
|         endtime<-dcast(tableR %>% filter(Volume < input$cutoff), `ID animal`+Group~., value.var = "Timepoint", fun.aggregate = function(x){max(as.numeric(as.character(x)))}) %>% rename("end"=".") | |
|         endtime["Dead"]<-dcast(tableR, `ID animal`+Group~., value.var = "Volume", fun.aggregate = function(x){max(as.numeric(as.character(x)))}) %>% pull(".") > input$cutoff | |
|         table_tumor<<-endtime | |
|          | |
|         g<-ggsurvplot(survfit(Surv(table_tumor$end, table_tumor$Dead) ~ table_tumor$Group, data=table_tumor), | |
|                             pval = T, pval.method = T, | |
|                             # legend.labs = paste(c("< median", ">= median"), "MICA"), | |
|                             ggtheme=theme_classic(base_size=15) | |
|                             # palette = c("#E7B800", "#2E9FDF") | |
|         ) | |
|         g | |
|       } | |
|     } | |
|   }) | |
|    | |
|   output$stats<-renderPrint({ | |
|     stattest<-"dunn" | |
|     oneside<-"" | |
|     if (!is.null(input$file_analy) & !is.null(analysis$taula_def)){ | |
|       observeEvent(analysis$taula_def, {}) | |
|       table<-analysis$taula_def | |
|       if (input$vacc == "No"){ | |
|         table<-filter(table, !is.na(Volume)) | |
|         summary(aov(Volume~Group+Timepoint+Error(`ID animal`), data=table)) | |
|       }else{ | |
|         for (side in c("L","R")){ | |
|           tableR<-filter(table, `ID tumor` == side) %>% filter(!is.na(Volume)) | |
|           if (length(unique(tableR$Volume)) > 1 & length(unique(tableR$Timepoint)) > 1){ | |
|             print(paste0("Side: ",side)) | |
|             # print(summary(aov(Volume~Group+Timepoint+Error(paste0(ID animal,Cage)), data=tableR))) | |
|             print(summary(aov(Volume~Group+Timepoint+Error(`ID animal`), data=tableR))) | |
|           } | |
|         } | |
|       } | |
|     } | |
|   }) | |
|   output$tab_stats<-renderTable({ | |
|     stattest<-"dunn" | |
|     oneside<-"" | |
|     if (!is.null(input$file_analy) & !is.null(analysis$taula_def)){ | |
|       table<-analysis$taula_def | |
|       table_stats<-list() | |
|       if (input$vacc == "No"){ | |
|         table<-table%>%filter(!is.na(Volume)) | |
|         if (length(unique(table$Volume)) > 1){ | |
|           table_stats<-multi_stats(table, "Volume", "Timepoint", "Group", stat.test=stattest)   | |
|         } | |
|         table_kw<-as.data.frame(matrix(nrow=0, ncol=2)) | |
|         for (point in unique(table$Timepoint)){ | |
|           len_group<-length(unique(table %>% filter(Timepoint == point) %>% pull(Group))) | |
|           if (len_group > 1){ | |
|             table_kw<-rbind(table_kw, data.frame(point,kruskal.test(table %>% filter(Timepoint == point) %>% pull(Volume), table %>% filter(Timepoint == point) %>% pull(Group))[3][[1]])) | |
|           } | |
|         } | |
|         colnames(table_kw)<-c("Timepoint", "KW-p.val") | |
|         table_stats<-merge(table_stats, table_kw) | |
|          | |
|       }else{ | |
|         for (side in c("L","R")){ | |
|           tableR<-filter(table, `ID tumor` == side) %>% filter(!is.na(Volume)) | |
|           if (length(unique(tableR$Volume)) > 1){ | |
|             table_stats[[side]]<-multi_stats(tableR, "Volume", "Timepoint", "Group", stat.test=stattest)   | |
|           } | |
|           table_kw<-as.data.frame(matrix(nrow=0, ncol=2)) | |
|           for (point in unique(tableR$Timepoint)){ | |
|             len_group<-length(unique(tableR %>% filter(Timepoint == point) %>% pull(Group))) | |
|             if (len_group > 1){ | |
|               table_kw<-rbind(table_kw, data.frame(point,kruskal.test(tableR %>% filter(Timepoint == point) %>% pull(Volume), tableR %>% filter(Timepoint == point) %>% pull(Group))[3][[1]])) | |
|             } | |
|           } | |
|           colnames(table_kw)<-c("Timepoint", "KW-p.val") | |
|           table_stats[[side]]<-merge(table_stats[[side]], table_kw) | |
|         } | |
|       } | |
|       table_stats_def<-bind_rows(table_stats, .id = "ID tumor") | |
|       if (input$filter_stats == T){ | |
|         table_stats_def %>% filter(p.adj < 0.05) | |
|       }else{ | |
|         table_stats_def  | |
|       } | |
|     } | |
|   }) | |
|    | |
|   output$downloadVolume <- downloadHandler( | |
|      | |
|     filename = function() { | |
|       paste("invivo-vols", ".xlsx", sep="") | |
|     }, | |
|     content = function(file){ | |
|       dtemplate<-analysis$taula_vol | |
|       write.xlsx(dtemplate,file) | |
|     } | |
|   ) | |
|    | |
|   ##Exportar | |
|   output$expPlotUI<- renderUI({ | |
|     observeEvent(analysis$taula_def, {}) | |
|     if (!is.null(input$file_analy) & !is.null(analysis$taula_def)){ | |
|       plotOutput("expPlot", width=paste0(input$width/10,"px"), height = paste0(input$height/10, "px")) | |
|     } | |
|   }) | |
|    | |
|   output$expPlot <- renderPlot({ | |
|     observeEvent(analysis$taula_def, {}) | |
|     if (!is.null(input$file_analy) & !is.null(analysis$taula_def)){ | |
|       table<-analysis$taula_def | |
|        | |
|       if (input$fig_id %in% c("Cinética Grupo", "Cinética Individual")){ | |
|         if (input$fig_id == "Cinética Grupo"){ | |
|           if (input$vacc == "Sí"){ | |
|             g<-ggplot(table, aes(as.numeric(as.character(Timepoint)), Volume, color=Group, group=Group))+ | |
|               scale_x_continuous(expand = expansion(mult = c(0,0.05)), limits = c(0, (round(max(as.numeric(as.character(table$Timepoint))) / 5)+1)*5))+ | |
|               facet_grid(factor(`ID tumor`, labels = c("Vaccination", "Rechallenge"))~., scale="free_y")+ | |
|               theme_bw()   | |
|           }else{ | |
|             g<-ggplot(table, aes(Timepoint, Volume, color=Group, group=Group))+ | |
|               theme_bw() | |
|           } | |
|         } | |
|         if (input$fig_id == "Cinética Individual"){ | |
|           if (input$vacc == "Sí"){ | |
|             g<-ggplot(table, aes(as.numeric(as.character(Timepoint)), Volume, color=Group, group=`ID animal`))+ | |
|               scale_x_continuous(expand = expansion(mult = c(0,0.05)), limits = c(0, (round(max(as.numeric(as.character(table$Timepoint))) / 5)+1)*5))+ | |
|               facet_grid(factor(`ID tumor`, labels = c("Vaccination", "Rechallenge"))~Group, scale="free_y")+ | |
|               theme_bw()   | |
|           }else{ | |
|             g<-ggplot(table, aes(Timepoint, Volume, color=Group, group=`ID animal`))+ | |
|               facet_wrap(.~Group)+ | |
|               theme_bw() | |
|           } | |
|         } | |
|          | |
|         g<-g+geom_errorbar(stat="summary", width=input$`errorbar-width`)+ | |
|           geom_line(stat="summary")+ | |
|           geom_point(stat="summary", size=input$`point-size`)+ | |
|           labs(x="Days after tumor challenge")+ | |
|           scale_y_continuous(expand = expansion(mult = c(0,0.05))) | |
|          | |
|         if (input$theme == "BW"){ | |
|           g<-g+theme_bw(base_size = input$`font-size`) | |
|         } | |
|         if (input$theme == "Classic"){ | |
|           g<-g+theme_classic(base_size = input$`font-size`)   | |
|         } | |
|         if (input$theme == "Default"){ | |
|           g<-g+theme_gray(base_size = input$`font-size`) | |
|         } | |
|         # g<-g+theme(axis.text.x=element_text(angle=45, hjust=1)) | |
|         if (input$legend == F){ | |
|           g<-g+guides(color=FALSE, fill=FALSE) | |
|         } | |
|         if (input$colors != ""){ | |
|           v_col<-strsplit(input$colors, ",")[[1]] | |
|           g<-g+scale_color_manual(values=v_col)+ | |
|             scale_fill_manual(values=v_col) | |
|         } | |
|         if (input$logscale == T){ | |
|           g<-g+scale_y_log10() | |
|         } | |
|       }else{ | |
|         gg_color_hue <- function(n, l=65) { | |
|           hues <- seq(15, 375, length=n+1) | |
|           hcl(h=hues, l=l, c=100)[1:n] | |
|         } | |
|         if (input$vacc == "Sí"){ | |
|           g<-list() | |
|           count<-1 | |
|           for (side in c("L","R")){ | |
|             tableR<-filter(table, `ID tumor` == side) %>% filter(!is.na(Volume)) | |
|             endtime<-dcast(tableR %>% filter(Volume < input$cutoff), Cage+`ID animal`+`ID tumor`+Group~., value.var = "Timepoint", fun.aggregate = function(x){max(as.numeric(as.character(x)))}) %>% rename("end"=".") | |
|             endtime["Dead"]<-dcast(tableR, Cage+`ID animal`+`ID tumor`+Group~., value.var = "Volume", fun.aggregate = function(x){max(as.numeric(as.character(x)))}) %>% pull(".") > input$cutoff | |
|             table_tumor<-endtime | |
|             if (input$colors != ""){ | |
|               col<-input$colors | |
|             }else{ | |
|               col<-gg_color_hue(length(unique(endtime$Group))) | |
|             } | |
|             g[[count]]<-ggsurvplot(survfit(Surv(table_tumor$end, table_tumor$Dead) ~ table_tumor$Group, data=table_tumor), | |
|                                 pval = T, pval.method = T, | |
|                                 title = side, | |
|                                 # legend.labs = paste(c("< median", ">= median"), "MICA"), | |
|                                 ggtheme=theme_classic(base_size=input$`font-size`), | |
|                                 palette = col | |
|             ) | |
|             count<-count+1 | |
|           } | |
|           g_surv_vacc<-g | |
|            | |
|         }else{ | |
|           tableR<-table %>% filter(!is.na(Volume)) | |
|           endtime<-dcast(tableR %>% filter(Volume < input$cutoff), `ID animal`+Group~., value.var = "Timepoint", fun.aggregate = function(x){max(as.numeric(as.character(x)))}) %>% rename("end"=".") | |
|           endtime["Dead"]<-dcast(tableR, `ID animal`+Group~., value.var = "Volume", fun.aggregate = function(x){max(as.numeric(as.character(x)))}) %>% pull(".") > input$cutoff | |
|           table_tumor<-endtime | |
|           if (input$colors != ""){ | |
|             col<-input$colors | |
|           }else{ | |
|             col<-gg_color_hue(length(unique(table_tumor$Group))) | |
|           } | |
|           g<-ggsurvplot(survfit(Surv(table_tumor$end, table_tumor$Dead) ~ table_tumor$Group, data=table_tumor), | |
|                         pval = T, pval.method = T, | |
|                         # legend.labs = paste(c("< median", ">= median"), "MICA"), | |
|                         ggtheme=theme_classic(base_size=input$`font-size`), | |
|                         palette = col | |
|           ) | |
|         } | |
|       } | |
|        | |
|       if (input$vacc == "Sí" & input$fig_id == "Survival"){ | |
|         dades$plot<<-g_surv_vacc | |
|         arrange_ggsurvplots(g, nrow=2, ncol=1) | |
|       }else{ | |
|           dades$plot<<-g | |
|           g | |
|       } | |
|     } | |
|   }, res=72) | |
|    | |
|   output$downloadPicture <- downloadHandler( | |
|     filename = function() { | |
|       paste("Figura", ".zip", sep="") | |
|     }, | |
|     content = function(file){ | |
|       # tempReport <- file.path(tempdir(), "elispots.Rmd") | |
|       # file.copy("elispots.Rmd", tempReport, overwrite = TRUE) | |
|       png("invivo.png", width = input$width, height=input$height, units = "px", res=720) | |
|       if (input$fig_id == "Survival"){ | |
|         if (input$vacc == "Sí"){ | |
|           arrange_ggsurvplots(dades$plot, nrow=2, ncol=1)  | |
|         }else{ | |
|           arrange_ggsurvplots(list(dades$plot), ncol=1)   | |
|         } | |
|         }else{plot(dades$plot)} | |
|       dev.off() | |
|       if (input$fig_id == "Survival"){ | |
|         if (input$vacc == "Sí"){ | |
|           invivo.plot<-arrange_ggsurvplots(dades$plot, nrow=2, ncol=1)  | |
|         }else{ | |
|           invivo.plot<-arrange_ggsurvplots(list(dades$plot), ncol=1)   | |
|         } | |
|       }else{invivo.plot<-dades$plot} | |
|       save(invivo.plot, file="invivoplot.RObject") | |
|       zip(file, | |
|           c("invivo.png", "invivoplot.RObject") | |
|       ) | |
|     }) | |
| 
 | |
|    | |
| } | |
| 
 | |
| # Run the application  | |
| shinyApp(ui = ui, server = server) |