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.

1059 lines
44 KiB

##V2.0
library(shiny)
library(reshape2)
library(openxlsx)
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),
uiOutput('ncages'),
uiOutput('ntumors'),
# selectInput(inputId = "measure_sys", "Sistema de medida", selected = "L-W-D", choices = c("L-W-D","Min-Max","Absorbance")),
uiOutput('day_vol'),
uiOutput('lowcut'),
uiOutput('upcut'),
uiOutput('goButton'),
uiOutput('iterations'),
downloadButton("downloadData", "Descargar Excel")
),
mainPanel(
plotOutput("firstPlot"),
plotOutput("distPlot"),
tableOutput("distTable"),
tableOutput("distTableAll")
)
),
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"),
checkboxInput("increase_volume","Usar Incremento de Volumen"),
checkboxInput("operated","Cortar al operar", value = TRUE),
checkboxInput("dead","Eliminar ratones muertos", value = FALSE),
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'),
selectInput("unit_fact", "Factor de unidad", choices = c("0.001","1","1000"), selected="1"),
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=""),
textInput("xaxis", label="Etiqueta Eje X", value=""),
textInput("yaxis", label="Etiqueta Eje Y", value=""),
sliderInput("errorbar-width", "% Ancho errorbars", min=0.0, max=1, step=0.05, value=0.05),
sliderInput("line-size", "Tamaño línea", min=0.1, max=3, step=0.1, value=0.5),
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 ------------------------------------------------------------------
# Diseño
dades<-reactiveValues()
dades$taula<-NULL
dades$groups<-NULL
dades$sex<-NULL
dades$db<-NULL
observe({
if (!is.null(input$file_sizes)){
table<-read.xlsx(input$file_sizes$datapath, sheet = 1, check.names = F, sep.names = " ", detectDates = T,cols=1:11)
if("ID.animal" %in% colnames(table)){
table<-table %>%
rename(Animal=`ID.animal`, Side=`ID.tumor`)
table<-table %>% gather(DayPostInoc, Value, which(!is.na(as.numeric(colnames(table))))) %>%
relocate(DayPostInoc, .before = Group) %>% spread(DPV, Value) %>%
rename(Long=Major, Wide=Minor) %>%
add_column(Date="", .after = "Animal") %>%
add_column(Weight="", .after="Group") %>%
add_column(Volume="",Observations="") %>%
relocate(Side, .after = "Group")
table$DayPostInoc<-as.numeric(table$DayPostInoc)
}
table$Date<-format(table$Date, format="%d/%m/%Y")
if ("sex" %in% colnames(table)){table<-select(table, -sex)}
for (i in 1:nrow(table)){
long<-as.numeric(gsub(",",".",strsplit(as.character(table[i,"Long"]),"+", fixed = T)[[1]]))
wide<-as.numeric(gsub(",",".",strsplit(as.character(table[i,"Wide"]),"+", fixed = T)[[1]]))
table[i,"Volume"]<-sum(sapply(1:length(long), function(x) (long[x]*wide[x]*wide[x])*(pi/6)))
}
table$Volume<-as.numeric(table$Volume)
if ("Cage" %in% colnames(table)){
table$Animal<-paste0(table$Cage, table$Animal)
table<-table[,-which(colnames(table) == "Cage")]
}
dades$taula<-table
dades$groups<-read.xlsx(input$file_sizes$datapath, sheet = "Groups", colNames=F)[,1]
if (readxl::excel_sheets(input$file_sizes$datapath) %>% length > 2){
dades$sex<-read.xlsx(input$file_sizes$datapath, sheet = 3, sep.names = " ")
}
}
})
output$firstPlot <- renderPlot({
observeEvent(dades$taula, {})
if (!is.null(dades$taula)){
ggplot(dades$taula %>% filter(DayPostInoc == input$day_vol), aes(x="1", y=Volume))+
geom_hline(yintercept = c(input$lowcut, input$upcut), color="red")+
geom_quasirandom(width=0.2)
}
})
output$day_vol<-renderUI({
if (!is.null(dades$taula)){
selectInput("day_vol", "Día para volúmenes", choices = sort(unique(dades$taula$DayPostInoc)))
}
})
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)){
taula<-dades$taula %>% filter(DayPostInoc == input$day_vol)
cut.max<-round(max(taula$Volume, na.rm = T), 2)
step<-round(max(taula$Volume, na.rm = T)/100, 2)
sliderInput("lowcut", "Corte inferior", min=0, max=cut.max, step=step, value=0)
}
})
output$upcut<-renderUI({
if (!is.null(dades$taula)){
taula<-dades$taula %>% filter(DayPostInoc == input$day_vol)
cut.max<-round(max(taula$Volume, na.rm = T), 2)+0.01
step<-round(max(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)
}
})
output$ntumors<-renderUI({
if (is.null(dades$taula)){
selectInput("ntumors", "Tumores por ratón", choices = c(1,2), selected = 2)
}
})
grafic<-eventReactive(input$goButton,{
df<-dades$taula %>% filter(DayPostInoc == input$day_vol)
# print(df)
df<-df[!is.na(df$Volume),]
up_cuttof<-input$upcut
low_cuttof<-input$lowcut
df<-df[df$Volume < up_cuttof & df$Volume >= low_cuttof,]
if (is.null(dades$sex)){
df<-add_column(df, sex="undefined")
}else{
df<-merge(df, dades$sex)
}
# df["Mouse"]<-gsub("[a-zA-Z]", "", df$MouseID)
s<-shapiro.test(df$Volume)[[2]]
ngroup<-length(dades$groups)
df_def<-list()
for (sex.var in unique(df$sex)){
df_sex<-df %>% filter(`sex` == sex.var)
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_sex$Animal))/ngroup)), length(unique(df_sex$Animal)))
df_sex<-merge(df_sex[,c("Animal", "Side","Volume")], data.frame("Animal"=unique(df_sex$Animal), "group"=as.factor(ind),check.names=F))
# print(df_sex)
if ((nrow(df_sex)/ngroup) %% 2 == 0){
interr<-any(table(df_sex$group) < floor(nrow(df_sex)/ngroup) | table(df_sex$group) > ceiling(nrow(df_sex)/ngroup))
}else{
# interr<-any(table(df_sex$group) < (floor(nrow(df_sex)/ngroup)-1) | table(df_sex$group) > (ceiling(nrow(df_sex)/ngroup)+1))
interr<-diff(range(table(ind))) > 1
}
}
ind.list[[data]]<-df_sex[,c("Animal","Side","group","Volume")]
lvn.list[data]<-leveneTest(Volume ~ group, data = df_sex[,3:4])[[2]][1]
if (s < 0.05){
k<-kruskal.test(df_sex$Volume,df_sex$group)
test.list[data]<-k[[1]][1]
pval.list[data]<-k[[3]][1]
}else{
res.aov<-aov(Volume~group, data=df_sex)
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])]))[1]
# print(df_sex)
df_def[[sex.var]]<-merge(df_sex %>% select(-group), ind.list[[index]])
}
df_def<-do.call(rbind, c(df_def, make.row.names=F))
# lapply(df_def, function(x) x %>% as_tibble %>% print(n=Inf))
# df_def<-rbind(df_def[[1]], df_def[[2]], make.row.names=F)
if ("Group" %in% colnames(df_def)){
df_def<-df_def %>% select(-"Group")
}
df_def<-merge(
if(!is.null(dades$sex)){merge(dades$taula %>% filter(DayPostInoc == input$day_vol), dades$sex)%>% select(-Group)}else{
dades$taula %>% filter(DayPostInoc == input$day_vol) %>% add_column(sex="undefined")} %>% select(-Group),
df_def[,c("Animal", "group")] %>% unique, all=T, by="Animal")
df_def<-df_def %>% rename(Group=group)
df_def<-select(df_def, Animal, sex, Date, DayPostInoc, Group, Side, Weight, Long, Wide, Volume, Observations)
# if("DPV" %in% colnames(df_def)){df_def<-select(df_def, c(`ID animal`, `sex`,`ID tumor`, Volume, Cage, Major, Minor, group))}
# if("TS-Deep" %in% colnames(df_def)){df_def<-select(df_def, c(`ID animal`, `sex`,`ID tumor`, Volume, Cage, `TS-Deep`,`TS-Length`,`TS-Width`, group))}
df_def[!paste0(df_def$Animal, df_def$Side) %in% paste0(df$Animal, df$Side),"Group"]<-NA
dades$db<-df_def
if (is.null(dades$sex)){
ggplot(df_def, aes(Group, Volume))+
geom_boxplot(outlier.alpha = F)+
geom_jitter(width=0.25)+
geom_point(stat="summary", color="blue", size=3)+
theme(axis.text.x = element_text(angle=90, hjust=1, vjust=0.5))
}else{
ggarrange(
ggplot(df_def, aes(Group, Volume))+
geom_boxplot(outlier.alpha = F)+
geom_jitter(width=0.25, aes(color=sex))+
geom_point(stat="summary", color="blue", size=3)+
theme(axis.text.x = element_text(angle=90, hjust=1, vjust=0.5)),
# lims(y=c(0,max(df_def$Volume)+10))
ggarrange(
ggplot(df_def, aes(sex, Volume))+
geom_boxplot(outlier.alpha = F)+
geom_quasirandom(width=0.3),
ggplot(df_def, aes(Group, fill=sex))+
geom_bar(stat="count", color="black", position="dodge")+
guides(fill="none")+
theme(axis.text.x = element_text(angle=90, hjust=1, vjust=0.5)), ncol = 1, heights = c(0.35, 0.65)),
nrow = 1, aligh="h", widths = c(0.65, 0.35))
}
})
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$distTableAll <- renderTable({
observeEvent(dades$db, {})
if (!is.null(dades$db)){
df<-dades$db
df %>% arrange(Group)
}
})
output$downloadData <- downloadHandler(
filename = function() {
paste("invivo", ".xlsx", sep="")
},
content = function(file){
ncages<-input$ncages
nrat_cage<-5
id_tumors<-c("L","R")[1:as.numeric(input$ntumors)]
# timepoint<-c(7,10,13,16,19,22,25)
if (!is.null(input$file_sizes)){
template<-dades$db %>% filter(!is.na(Group)) %>%
select(Animal, Group) %>% unique()
dtemplate<-merge(dades$taula %>% select(-Group), template) %>%
arrange(DayPostInoc, Animal, Side) %>%
select(Animal, Date, DayPostInoc, Group, Side,
Weight, Long, Wide, Volume, Observations)
}else{
template<-data.frame(
Cage=rep(LETTERS[1:ncages], each=nrat_cage*as.numeric(input$ntumors)),
Animal=rep(1:(nrat_cage*ncages), each=as.numeric(input$ntumors)),
Date="",
DayPostInoc="",
Group="",
Side=rep(id_tumors, nrat_cage*ncages),
Weight="",
Long="",
Wide="",
Volume="",
Observations=""
)
template<-template %>% mutate(Animal=paste0(Cage,Animal)) %>% select(-Cage)
dtemplate<-template
}
write.xlsx(list("Measures"=dtemplate, "Groups"=NULL,"Sex"=NULL), file)
}
)
# Análisis ----------------------------------------------------------------
analysis<-reactiveValues()
analysis$taula<-NULL
analysis$taula_def<-NULL
analysis$taula_vol<-NULL
observe({
if (!is.null(input$file_analy)){
table<-read.xlsx(input$file_analy$datapath, sheet = 1, check.names = F, sep.names = " ", detectDates = T,cols=1:11)
if("ID.animal" %in% colnames(table)){
table<-table %>%
rename(Animal=`ID.animal`, Side=`ID.tumor`)
table<-table %>% gather(DayPostInoc, Value, which(!is.na(as.numeric(colnames(table))))) %>%
relocate(DayPostInoc, .before = Group) %>% spread(DPV, Value) %>%
rename(Long=Major, Wide=Minor) %>%
add_column(Date="", .after = "Animal") %>%
add_column(Weight="", .after="Group") %>%
add_column(Volume="",Observations="") %>%
relocate(Side, .after = "Group")
table$DayPostInoc<-as.numeric(table$DayPostInoc)
}
table$Date<-format(table$Date, format="%d/%m/%Y")
if ("sex" %in% colnames(table)){table<-select(table, -sex)}
for (i in 1:nrow(table)){
long<-as.numeric(gsub(",",".",strsplit(as.character(table[i,"Long"]),"+", fixed = T)[[1]]))
wide<-as.numeric(gsub(",",".",strsplit(as.character(table[i,"Wide"]),"+", fixed = T)[[1]]))
table[i,"Volume"]<-sum(sapply(1:length(long), function(x) (long[x]*wide[x]*wide[x])*(pi/6)))
}
table$Volume<-as.numeric(table$Volume)
if ("Cage" %in% colnames(table)){
table$Animal<-paste0(table$Cage, table$Animal)
table<-table[,-which(colnames(table) == "Cage")]
}
## Autocompletado de grupo
table_group<-merge(
table %>% select(Animal, Group) %>% unique() %>% group_by(Animal) %>% count(),
table %>% select(Animal, Group) %>% unique()
) %>% filter(!is.na(Group) | Group != "") %>% select(-n)
table<-merge(
table %>% select(-Group),
table_group
) %>% relocate(Group, .after = DayPostInoc) %>%
arrange(DayPostInoc, Animal, Side)
if("Groups" %in% readxl::excel_sheets(input$file_analy$datapath)){
levels<-read.xlsx(input$file_analy$datapath, sheet = "Groups", colNames=F)[,1]
print(levels)
table$Group<-factor(table$Group, levels=levels)
table<-filter(table, !is.na(Group))
}else(table$Group<-factor(table$Group))
print(str(table))
analysis$taula<-table
}
})
output$cutoffUI<-renderUI({
if (!is.null(analysis$taula)){
observeEvent(analysis$taula, {})
max_val<-max(analysis$taula$Volume, na.rm = T)
# print(max_val)
sliderInput("cutoff", "Cutoff para Survival", min=0, max=round(max_val, digits=2), step=round(max_val, digits=2)/200, value=max_val)
}
})
output$ntable<-renderTable({
if (!is.null(input$file_analy)){
observeEvent(analysis$taula, {})
stattest<-"dunn"
oneside<-""
table<-analysis$taula
table<-table %>% filter(!is.na(Group))
if (input$increase_volume){
timepoints<-unique(table$Timepoint)
table<-table %>% select(-Major, -Minor) %>%
spread(Timepoint, Volume) %>%
mutate(across(all_of(timepoints), function(x){(x*100/`0`)-100})) %>%
gather(Timepoint, Volume, -`ID animal`, -`ID tumor`, -Group) %>%
mutate(Volume=case_when(Volume < 0 ~ 0, T~Volume))
}
table %>% group_by(Group, DayPostInoc, Side) %>% count() %>% spread(DayPostInoc, n)
}
})
output$cin_group<-renderPlot({
if (!is.null(input$file_analy) & !is.null(analysis$taula)){
observeEvent(analysis$taula, {})
table<-analysis$taula
print(table)
animals<-unique(table$Animal)
sides<-unique(table$Side)
groups<-table %>% select(Animal, Group) %>% unique() %>% pull(Group)
basal<-data.frame(
Animal=rep(animals, each=length(sides)),
Date="",
DayPostInoc=0,
Group=rep(groups, each=length(sides)),
Side=rep(sides, length(animals)),
Weight="",
Long="",
Wide="",
Volume=0,
Observations=""
)
if (!(0 %in% table$DayPostInoc) | sum(table[test$DayPostInoc == 0,"Volume"],na.rm = T) == 0){
table<-rbind(table, basal)
}
if (input$vacc == "Sí"){
firstoper<- filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "*") %>%
select(DayPostInoc, Side) %>% unique() %>%
group_by(Side) %>% summarise(FirstOper=min(DayPostInoc))
deadmice<-filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "+") %>%
pull(Animal)
print(deadmice)
if (input$operated == TRUE & nrow(firstoper) > 0){
for (i in 1:nrow(firstoper)){
table<-table %>% filter(DayPostInoc < firstoper$FirstOper[i] | Side != firstoper$Side[i])
}
}else{
if(input$dead == TRUE){
table<-table %>% filter(!Animal %in% deadmice)
}
}
ggplot(table, aes(DayPostInoc, Volume, color=Group, group=Group))+
geom_errorbar(stat="summary", width=0.05)+
geom_line(stat="summary")+
geom_point(stat="summary")+
facet_grid(factor(Side, labels = c("Vaccination", "Rechallenge"))~., scale="free_y")+
labs(x="Days after tumor inoculation")+
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(table$DayPostInoc) / 5)+1)*5))+
theme_bw()
}else{
firstoper<- filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "*") %>%
pull(DayPostInoc) %>% min(na.rm = T)
if (firstoper == Inf){firstoper<-c()}
if (input$operated == TRUE & length(firstoper) > 0){
table<-table %>% filter(DayPostInoc < firstoper)
}else{
deadmice<-filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "+") %>%
pull(Animal)
if(input$dead == TRUE){
table<-table %>% filter(!Animal %in% deadmice)
}
}
ggplot(table, aes(DayPostInoc, 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)){
observeEvent(analysis$taula, {})
table<-analysis$taula
animals<-unique(table$Animal)
sides<-unique(table$Side)
groups<-table %>% select(Animal, Group) %>% unique() %>% pull(Group)
basal<-data.frame(
Animal=rep(animals, each=length(sides)),
Date="",
DayPostInoc=0,
Group=rep(groups, each=length(sides)),
Side=rep(sides, length(animals)),
Weight="",
Long="",
Wide="",
Volume=0,
Observations=""
)
if (!(0 %in% table$DayPostInoc) | sum(test[table$DayPostInoc == 0,"Volume"],na.rm = T) == 0){
table<-rbind(table, basal)
}
if (input$vacc == "Sí"){
firstoper<- filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "*") %>%
select(DayPostInoc, Side) %>% unique() %>%
group_by(Side) %>% summarise(FirstOper=min(DayPostInoc))
if (input$operated == TRUE & nrow(firstoper) > 0){
for (i in 1:nrow(firstoper)){
table<-table %>% filter(DayPostInoc < firstoper$FirstOper[i] | Side != firstoper$Side[i])
}
}else{
if(input$dead == TRUE){
deadmice<-filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "+") %>%
pull(Animal)
table<-table %>% filter(!Animal %in% deadmice)
}
}
ggplot(table, aes(DayPostInoc, Volume, color=Group, group=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(table$DayPostInoc) / 5)+1)*5))+
facet_grid(factor(Side, labels = c("Vaccination", "Rechallenge"))~Group, scale="free_y")+
labs(x="Days after tumor inoculation")+
theme_bw()
}else{
firstoper<- filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "*") %>%
pull(DayPostInoc) %>% min(na.rm = T)
if (firstoper == Inf){firstoper<-c()}
if (input$operated == TRUE & length(firstoper) > 0){
table<-table %>% filter(DayPostInoc < firstoper)
}else{
deadmice<-filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "+") %>%
pull(Animal)
if(input$dead == TRUE){
table<-table %>% filter(!Animal %in% deadmice)
}
}
ggplot(table, aes(DayPostInoc, Volume, color=Group, group=paste0(Animal, Side)))+
# 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 inoculation")+
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)){
observeEvent(analysis$taula, {})
table<-analysis$taula
if (input$vacc == "Sí"){
firstoper<- filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "*") %>%
select(DayPostInoc, Side) %>% unique() %>%
if (firstoper == Inf){firstoper<-c()}
if (input$operated == TRUE & length(firstoper) > 0){
for (i in 1:nrow(firstoper)){
table<-table %>% filter(DayPostInoc < firstoper$FirstOper[i] | Side != firstoper$Side[i])
}
}else{
if(input$dead == TRUE){
deadmice<-filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "+") %>%
pull(Animal)
table<-table %>% filter(!Animal %in% deadmice)
}
}
g<-list()
for (side in c("L","R")){
tableR<-filter(table, Side == side) %>% filter(!is.na(Volume))
endtime<-dcast(tableR %>% filter(Volume < input$cutoff), Animal+Side+Group~., value.var = "DayPostInoc", fun.aggregate = function(x){max(as.numeric(as.character(x)))}) %>% rename("end"=".")
endtime["Dead"]<-dcast(tableR, Animal+Side+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(end, Dead) ~ 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{
firstoper<- filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "*") %>%
pull(DayPostInoc) %>% min(na.rm = T)
print(firstoper)
if (input$operated == TRUE & nrow(firstoper) > 0){
table<-table %>% filter(DayPostInoc < firstoper)
}else{
deadmice<-filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "+") %>%
pull(Animal)
if(input$dead == TRUE){
table<-table %>% filter(!Animal %in% deadmice)
}
}
tableR<-table %>% filter(!is.na(Volume))
endtime<-dcast(if(length(unique(tableR$DayPostInoc)) > 1){tableR %>% filter(Volume < input$cutoff)}else{tableR}, Animal+Side+Group~.,
value.var = "DayPostInoc", fun.aggregate = function(x){max(as.numeric(as.character(x)))}) %>% rename("end"=".")
endtime["Dead"]<-dcast(tableR, Animal+Side+Group~., value.var = "Volume", fun.aggregate = function(x){max(as.numeric(as.character(x)))}) %>% pull(".") >= input$cutoff
table_tumor<<-endtime
g<-ggsurvplot(survfit(Surv(end, Dead) ~ 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)){
observeEvent(analysis$taula, {})
table<-analysis$taula
if (input$vacc == "No"){
table<-filter(table, !is.na(Volume))
summary(aov(Volume~Group+DayPostInoc+Error(Animal+Side), data=table))
}else{
for (side in c("L","R")){
tableR<-filter(table, Side == side) %>% filter(!is.na(Volume))
if (length(unique(tableR$Volume)) > 1 & length(unique(tableR$DayPostInoc)) > 1){
print(paste0("Side: ",side))
print(summary(aov(Volume~Group+DayPostInoc+Error(Animal), data=tableR)))
}
}
}
}
})
output$tab_stats<-renderTable({
stattest<-"dunn"
oneside<-""
if (!is.null(input$file_analy) & !is.null(analysis$taula)){
table<-analysis$taula
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", "DayPostInoc", "Group", stat.test=stattest)
}
table_kw<-as.data.frame(matrix(nrow=0, ncol=2))
for (point in unique(table$DayPostInoc)){
len_group<-length(unique(table %>% filter(DayPostInoc == point) %>% pull(Group)))
if (len_group > 1){
table_kw<-rbind(table_kw, data.frame(point,kruskal.test(table %>% filter(DayPostInoc == point) %>% pull(Volume), table %>% filter(DayPostInoc == point) %>% pull(Group))[3][[1]]))
}
}
colnames(table_kw)<-c("DayPostInoc", "KW-p.val")
table_stats<-merge(table_stats, table_kw)
}else{
for (side in c("L","R")){
tableR<-filter(table, Side == side) %>% filter(!is.na(Volume))
if (length(unique(tableR$Volume)) > 1){
table_stats[[side]]<-multi_stats(tableR, "Volume", "DayPostInoc", "Group", stat.test=stattest)
}
table_kw<-as.data.frame(matrix(nrow=0, ncol=2))
for (point in unique(tableR$DayPostInoc)){
len_group<-length(unique(tableR %>% filter(DayPostInoc == point) %>% pull(Group)))
if (len_group > 1){
table_kw<-rbind(table_kw, data.frame(point,kruskal.test(tableR %>% filter(DayPostInoc == point) %>% pull(Volume), tableR %>% filter(DayPostInoc == point) %>% pull(Group))[3][[1]]))
}
}
colnames(table_kw)<-c("DayPostInoc", "KW-p.val")
table_stats[[side]]<-merge(table_stats[[side]], table_kw)
}
}
table_stats_def<-bind_rows(table_stats, .id = "Side")
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
# print(str(dtemplate))
write.xlsx(dtemplate,file, )
}
)
# Exportar ----------------------------------------------------------------
output$expPlotUI<- renderUI({
observeEvent(analysis$taula, {})
if (!is.null(input$file_analy) & !is.null(analysis$taula)){
plotOutput("expPlot", width=paste0(input$width/10,"px"), height = paste0(input$height/10, "px"))
}
})
output$expPlot <- renderPlot({
observeEvent(analysis$taula, {})
if (!is.null(input$file_analy) & !is.null(analysis$taula)){
table<-analysis$taula
table$Volume<-table$Volume*as.numeric(input$unit_fact)
animals<-unique(table$Animal)
sides<-unique(table$Side)
groups<-table %>% select(Animal, Group) %>% unique() %>% pull(Group)
basal<-data.frame(
Animal=rep(animals, each=length(sides)),
Date="",
DayPostInoc=0,
Group=rep(groups, each=length(sides)),
Side=rep(sides, length(animals)),
Weight="",
Long="",
Wide="",
Volume=0,
Observations=""
)
table<-rbind(table, basal)
if (input$fig_id %in% c("Cinética Grupo", "Cinética Individual")){
if (input$fig_id == "Cinética Grupo"){
if (input$vacc == "Sí"){
firstoper<- filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "*") %>%
select(DayPostInoc, Side) %>% unique() %>%
group_by(Side) %>% summarise(FirstOper=min(DayPostInoc))
if (input$operated == TRUE){
for (i in 1:nrow(firstoper)){
table<-table %>% filter(DayPostInoc < firstoper$FirstOper[i] | Side != firstoper$Side[i])
}
}else{
if(input$dead == TRUE){
deadmice<-filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "+") %>%
pull(Animal)
table<-table %>% filter(!Animal %in% deadmice)
}
}
std<-function(x, na.rm=T){sd(x, na.rm=na.rm)/sqrt(length(x))}
errbar<-table %>% group_by(Group,Side,DayPostInoc) %>%
summarise(mean=mean(Volume, na.rm=T), std=std(Volume)) %>%
mutate(Timepoint2=as.numeric(as.character(DayPostInoc))) %>%
mutate(x=Timepoint2-input$`errorbar-width`, xend=Timepoint2+input$`errorbar-width`)
g<-ggplot(table, aes(DayPostInoc, Volume, color=Group, group=Group))+
geom_errorbar(stat="summary", width=0.05)+
geom_line(stat="summary")+
geom_point(stat="summary")+
facet_grid(factor(Side, labels = c("Vaccination", "Rechallenge"))~., scale="free_y")+
labs(x="Days after tumor inoculation")+
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(table$DayPostInoc) / 5)+1)*5))+
theme_bw()+
geom_segment(data=errbar, aes(y=mean, yend=mean+std, x=Timepoint2, xend=Timepoint2))+
geom_segment(data=errbar, aes(y=mean+std, yend=mean+std,
x=x,xend=xend))
}else{
firstoper<- filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "*") %>%
pull(DayPostInoc) %>% min(na.rm = T)
print(firstoper)
if (input$operated == TRUE){
table<-table %>% filter(DayPostInoc < firstoper)
}else{
deadmice<-filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "+") %>%
pull(Animal)
if(input$dead == TRUE){
table<-table %>% filter(!Animal %in% deadmice)
}
}
std<-function(x, na.rm=T){sd(x, na.rm=na.rm)/sqrt(length(x))}
errbar<-table %>% group_by(Group, DayPostInoc) %>%
summarise(mean=mean(Volume, na.rm=T), std=std(Volume)) %>%
mutate(Timepoint2=as.numeric(as.character(DayPostInoc))) %>%
mutate(x=Timepoint2-input$`errorbar-width`, xend=Timepoint2+input$`errorbar-width`)
g<-ggplot(table, aes(DayPostInoc, 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))+
geom_segment(data=errbar, aes(y=mean, yend=mean+std, x=Timepoint2, xend=Timepoint2))+
geom_segment(data=errbar, aes(y=mean+std, yend=mean+std,
x=x,xend=xend))
}
}
if (input$fig_id == "Cinética Individual"){
if (input$vacc == "Sí"){
firstoper<- filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "*") %>%
select(DayPostInoc, Side) %>% unique() %>%
group_by(Side) %>% summarise(FirstOper=min(DayPostInoc))
if (input$operated == TRUE){
for (i in 1:nrow(firstoper)){
table<-table %>% filter(DayPostInoc < firstoper$FirstOper[i] | Side != firstoper$Side[i])
}
}else{
if(input$dead == TRUE){
deadmice<-filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "+") %>%
pull(Animal)
table<-table %>% filter(!Animal %in% deadmice)
}
}
g<-ggplot(table, aes(as.numeric(as.character(DayPostInoc)), Volume, color=Group, group=Animal))+
scale_x_continuous(expand = expansion(mult = c(0,0.0)),
breaks=sort(unique(as.numeric(as.character(table$DayPostInoc)))),
limits = c(0, (round(max(as.numeric(as.character(table$DayPostInoc))) / 5)+1)*5))+
facet_grid(factor(Side, labels = c("Vaccination", "Rechallenge"))~Group, scale="free_y")+
theme_bw()
}else{
firstoper<- filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "*") %>%
pull(DayPostInoc) %>% min(na.rm = T)
print(firstoper)
if (input$operated == TRUE){
table<-table %>% filter(DayPostInoc < firstoper)
}else{
deadmice<-filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "+") %>%
pull(Animal)
if(input$dead == TRUE){
table<-table %>% filter(!Animal %in% deadmice)
}
}
g<-ggplot(table, aes(as.numeric(as.character(DayPostInoc)), Volume, color=Group, group=Animal))+
scale_x_continuous(expand = expansion(mult = c(0,0.0)),
breaks=sort(unique(as.numeric(as.character(table$DayPostInoc)))),
limits = c(0,max(as.numeric(as.character(table$DayPostInoc)))*1.1))+
facet_wrap(.~Group)+
theme_bw()
}
}
g<-g+
# geom_errorbar(stat="summary", width=input$`errorbar-width`)+
geom_line(stat="summary", size=input$`line-size`)+
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$xaxis != ""){
g<-g+xlab(input$xaxis)
}
if (input$yaxis != ""){
g<-g+ylab(input$yaxis)
}
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í"){
firstoper<- filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "*") %>%
select(DayPostInoc, Side) %>% unique() %>%
group_by(Side) %>% summarise(FirstOper=min(DayPostInoc))
if (input$operated == TRUE){
for (i in 1:nrow(firstoper)){
table<-table %>% filter(DayPostInoc < firstoper$FirstOper[i] | Side != firstoper$Side[i])
}
}else{
if(input$dead == TRUE){
deadmice<-filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "+") %>%
pull(Animal)
table<-table %>% filter(!Animal %in% deadmice)
}
}
g<-list()
count<-1
for (side in c("L","R")){
tableR<-filter(table, Side == side) %>% filter(!is.na(Volume))
endtime<-dcast(tableR %>% filter(Volume < (input$cutoff*as.numeric(input$unit_fact))), Animal+Side+Group~., value.var = "DayPostInoc", fun.aggregate = function(x){max(as.numeric(as.character(x)))}) %>% rename("end"=".")
endtime["Dead"]<-dcast(tableR, Animal+Side+Group~., value.var = "Volume", fun.aggregate = function(x){max(as.numeric(as.character(x)))}) %>% pull(".") > (input$cutoff*as.numeric(input$unit_fact))
table_tumor<-endtime
if (input$colors != ""){
col<-strsplit(input$colors, ",")[[1]]
}else{
col<-gg_color_hue(length(unique(endtime$Group)))
}
table_tumor$Group<-factor(table_tumor$Group, levels = levels(analysis$taula$Group))
g[[count]]<-ggsurvplot(survfit(Surv(end, Dead) ~ Group, data=table_tumor),
pval = T, pval.method = T,
title = side,
ggtheme=theme_classic(base_size=input$`font-size`),
palette = col
)
count<-count+1
}
g_surv_vacc<-g
}else{
firstoper<- filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "*") %>%
pull(DayPostInoc) %>% min(na.rm = T)
print(firstoper)
if (input$operated == TRUE){
table<-table %>% filter(DayPostInoc < firstoper)
}else{
deadmice<-filter(table, !is.na(substr(Observations,1,1)) & substr(Observations,1,1) == "+") %>%
pull(Animal)
if(input$dead == TRUE){
table<-table %>% filter(!Animal %in% deadmice)
}
}
tableR<-table %>% filter(!is.na(Volume))
endtime<-dcast(tableR %>% filter(Volume < (input$cutoff*as.numeric(input$unit_fact))), Animal+Group~., value.var = "DayPostInoc", fun.aggregate = function(x){max(as.numeric(as.character(x)))}) %>% rename("end"=".")
endtime["Dead"]<-dcast(tableR, Animal+Group~., value.var = "Volume", fun.aggregate = function(x){max(as.numeric(as.character(x)))}) %>% pull(".") > (input$cutoff*as.numeric(input$unit_fact))
table_tumor<-endtime
if (input$colors != ""){
col<-strsplit(input$colors, ",")[[1]]
}else{
col<-gg_color_hue(length(unique(table_tumor$Group)))
}
table_tumor$Group<-factor(table_tumor$Group, levels = levels(analysis$taula$Group))
g<-ggsurvplot(survfit(Surv(end, Dead) ~ Group, data=table_tumor),
pval = T, pval.method = T,
# 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)