International Rice Research Institute
Update app.R
298177b verified
Raw History Blame
33 kB
library(shiny)
library(shinyjs)
library(tidyverse)
library(DT)
library(readxl)
library(lme4)
library(emmeans)
library(plotly)
library(shinyWidgets)
library(ggplot2)
library(colourpicker) # Added for colourInput
# UI with updated styling, now including Descriptive Statistics and color options
ui <- fluidPage(
useShinyjs(),
tags$head(
tags$meta(charset = "UTF-8"),
tags$title("Phenotypic Analysis Dashboard"),
tags$link(rel = "stylesheet", href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"),
tags$style(HTML("
:root {
--primary: #1E3A8A; /* Dark blue for tabs */
--secondary: #6B8E23; /* Olive green */
--success: #32CD32; /* Lime Green */
--info: #4169E1; /* Royal Blue */
--warning: #FF8C00; /* Dark Orange */
--danger: #DC143C; /* Crimson */
--light: #D1D5DB; /* Grey for tab text */
--dark: #2F4F4F; /* Dark Slate Gray */
--background: #FFFFFF; /* White background */
--card-bg: #FFFFFF; /* White for cards */
}
body {
font-family: 'Poppins', sans-serif;
background: var(--background);
color: var(--dark);
overflow-x: hidden;
}
.container-fluid {
max-width: 1600px;
padding: 2.5rem;
margin: 0 auto;
}
.section {
margin-bottom: 30px;
background: var(--card-bg);
padding: 2.5rem;
border-radius: 15px;
box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
border: 1px solid rgba(30, 58, 138, 0.2);
}
h1, h2, h3 {
color: var(--primary);
border-bottom: 2px solid var(--secondary);
padding-bottom: 10px;
margin-bottom: 20px;
font-weight: 700;
}
.chart-container {
position: relative;
margin-bottom: 20px;
border-radius: 12px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
background: var(--card-bg);
padding: 1.5rem;
border: 1px solid rgba(30, 58, 138, 0.2);
min-height: 400px;
}
.insights {
margin-top: 20px;
padding: 20px;
background: #F5F5F5;
border-radius: 8px;
border-left: 4px solid var(--secondary);
font-size: 14px;
}
.upload-container {
padding: 20px;
text-align: center;
border: 2px dashed var(--primary);
border-radius: 8px;
margin-bottom: 25px;
background: #F9F9F9;
}
.upload-icon {
font-size: 48px;
color: var(--primary);
margin-bottom: 15px;
}
.btn-primary {
background: linear-gradient(135deg, var(--primary), var(--info));
border: none;
padding: 1rem 2.5rem;
border-radius: 8px;
font-weight: 600;
color: white;
transition: all 0.3s;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}
.btn-primary:hover {
background: linear-gradient(135deg, var(--info), var(--primary));
transform: translateY(-2px);
box-shadow: 0 6px 12px rgba(30, 58, 138, 0.3);
color: white;
}
.sidebar {
background: var(--card-bg);
color: var(--dark);
padding: 2rem;
height: 100vh;
position: fixed;
width: 280px;
box-shadow: 5px 0 15px rgba(0,0,0,0.1);
border-right: 1px solid var(--primary);
}
.sidebar-header {
padding: 20px;
background: linear-gradient(135deg, var(--primary), var(--info));
text-align: center;
border-bottom: 1px solid rgba(0,0,0,0.1);
border-radius: 10px;
margin-bottom: 20px;
color: white;
}
.sidebar-content {
padding: 15px;
}
.nav-link {
color: var(--dark);
padding: 12px 15px;
border-radius: 8px;
margin-bottom: 8px;
display: flex;
align-items: center;
transition: all 0.3s;
background: #F5F5F5;
}
.nav-link:hover, .nav-link.active {
color: white;
background: linear-gradient(90deg, var(--primary), var(--info));
transform: translateX(5px);
box-shadow: 0 4px 8px rgba(30, 58, 138, 0.3);
}
.nav-link i {
margin-right: 10px;
width: 20px;
text-align: center;
}
.main-content {
margin-left: 280px;
padding: 20px;
width: calc(100% - 280px);
min-height: 100vh;
background: var(--background);
}
.loader {
border: 5px solid #F5F5F5;
border-top: 5px solid var(--primary);
border-radius: 50%;
width: 50px;
height: 50px;
animation: spin 1s linear infinite;
margin: 20px auto;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.hidden {
display: none;
}
table.dataTable {
border-collapse: collapse;
width: 100%;
font-size: 16px;
background: var(--card-bg);
border-radius: 8px;
overflow: hidden;
}
th {
background: linear-gradient(45deg, var(--primary), var(--info));
color: white;
padding: 1.2rem;
font-weight: 700;
text-transform: uppercase;
}
td {
padding: 1.2rem;
border-bottom: 1px solid #F0F0F0;
transition: background 0.3s;
color: var(--dark);
}
tr:hover {
background: #F5F5F5;
}
.dataTables_wrapper {
color: var(--dark);
}
.status-card {
background: var(--card-bg);
padding: 20px;
border-radius: 10px;
text-align: center;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
border: 1px solid rgba(30, 58, 138, 0.2);
margin-bottom: 15px;
}
.status-card i {
font-size: 2rem;
color: var(--primary);
margin-bottom: 10px;
}
.status-card h4 {
color: var(--primary);
font-size: 1.5rem;
margin: 5px 0;
}
.status-card p {
color: var(--dark);
margin: 0;
}
.plotly-title {
font-size: 18px;
font-weight: bold;
color: var(--primary);
}
.plotly-annotation {
font-size: 14px;
color: var(--dark);
}
.color-picker-container {
background: #F9F9F9;
padding: 15px;
border-radius: 8px;
margin-bottom: 15px;
border: 1px solid #E0E0E0;
}
.color-picker-title {
font-weight: 600;
margin-bottom: 10px;
color: var(--primary);
}
"))
),
div(
class = "app-wrapper",
div(
class = "sidebar",
div(
class = "sidebar-header",
h3("📊 Phenotypic Data Analysis", style = "margin: 0; font-weight: 600; color: white;")
),
selectInput("lme4_selected_trait", "Select Trait for Detailed Analysis", choices = c()),
checkboxInput("lme4_include_interaction", "Include Environment:Genotype Interaction", value = FALSE),
# Color customization options
div(
class = "color-picker-container",
div(class = "color-picker-title", "🎨 Plot Colors"),
colourpicker::colourInput("color_primary", "Primary Color", value = "#1E3A8A"),
colourpicker::colourInput("color_secondary", "Secondary Color", value = "#6B8E23"),
colourpicker::colourInput("color_accent", "Accent Color", value = "#4169E1"),
colourpicker::colourInput("color_highlight", "Highlight Color", value = "#FF8C00"),
actionButton("apply_colors", "Apply Colors", class = "btn-primary", style = "width: 100%;")
),
div(
class = "sidebar-content",
div(
class = "nav flex-column", id = "lme4-v-pills-tab", role = "tablist",
tags$a(class = "nav-link active", `data-toggle` = "pill", href = "#lme4-upload", role = "tab",
icon("file-upload", class = "fas"), "📤 Upload Data"),
tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-descriptives", role = "tab",
icon("chart-line", class = "fas"), "📊 Descriptive Statistics"),
tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-blues", role = "tab",
icon("chart-bar", class = "fas"), "📈 Predicted Means"),
tags$a(class = "nav-link", `data-toggle` = "pill", href = "#lme4-correlations", role = "tab",
icon("link", class = "fas"), "🔗 Trait Correlations")
),
hr(style = "border-color: rgba(255,255,255,0.1);"),
div(
style = "padding: 15px; color: var(--light); font-size: 12px; text-align: center;",
p("LME4 Analysis Dashboard v1.1"),
p("© 2023 Statistical Genetics Lab")
)
)
),
div(
class = "main-content",
div(
class = "tab-content",
div(
class = "tab-pane fade show active", id = "lme4-upload", role = "tabpanel",
div(
class = "section",
h2("📤 Upload Your Data"),
div(
class = "upload-container",
div(class = "upload-icon", icon("cloud-upload-alt", class = "fas")),
h3("📁 Drag and drop your Excel file here", style = "color: var(--primary);"),
p("or", style = "margin: 10px 0;"),
fileInput("lme4_file", NULL, accept = c(".xlsx", ".xls"),
buttonLabel = "Browse Files", placeholder = "No file selected"),
p("📝 Supported formats: .xlsx, .xls", style = "color: var(--light); font-size: 14px;"),
div(id = "lme4_loader", class = "loader hidden")
),
verbatimTextOutput("lme4_data_preview"),
verbatimTextOutput("lme4_debug_log"),
div(
id = "lme4_data_stats", class = "hidden",
h3("📊 Data Overview"),
fluidRow(
column(3, div(class = "status-card card-1",
icon("columns", class = "fas"),
h4(textOutput("lme4_n_vars"), style = "font-weight: 600;"),
p("Variables")
)),
column(3, div(class = "status-card card-2",
icon("list", class = "fas"),
h4(textOutput("lme4_n_obs"), style = "font-weight: 600;"),
p("Observations")
)),
column(3, div(class = "status-card card-3",
icon("dna", class = "fas"),
h4(textOutput("lme4_n_geno"), style = "font-weight: 600;"),
p("Genotypes")
)),
column(3, div(class = "status-card card-4",
icon("globe", class = "fas"),
h4(textOutput("lme4_n_env"), style = "font-weight: 600;"),
p("Environments")
))
)
)
)
),
div(
class = "tab-pane fade", id = "lme4-descriptives", role = "tabpanel",
div(
class = "section",
h2("📊 Descriptive Statistics"),
div(
id = "lme4_descriptives_content",
div(class = "table-container", DTOutput("lme4_descriptives_table")),
div(class = "chart-container", plotlyOutput("lme4_descriptives_plot", height = "500px")),
div(
class = "insights",
h4("💡 Interpretation"),
p("Descriptive statistics provide an overview of central tendency, variability, and range for each trait. Coefficient of Variation (CV) indicates relative variability; lower CV suggests more consistent data across observations.")
)
),
div(
id = "lme4_descriptives_placeholder", class = "text-center",
icon("chart-line", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
h4("📤 Upload data to see descriptive statistics", style = "color: var(--light);")
)
)
),
div(
class = "tab-pane fade", id = "lme4-blues", role = "tabpanel",
div(
class = "section",
h2("📈 Predicted Means (BLUEs)"),
div(
id = "lme4_blues_content",
div(class = "chart-container", plotlyOutput("lme4_blues_plot", height = "500px")),
div(class = "table-container", DTOutput("lme4_blues_table")),
div(
class = "insights",
h4("💡 Interpretation"),
p("The G×E interaction plot shows genotype performance across environments. Stable genotypes have consistent values, while environment-specific genotypes vary. Use for selecting broadly adapted or specific genotypes.")
)
),
div(
id = "lme4_blues_placeholder", class = "text-center",
icon("chart-bar", class = "fas", style = "font-size: 72px; color: var(--light; margin: 30px 0;"),
h4("📤 Upload data to see predicted means", style = "color: var(--light);")
)
)
),
div(
class = "tab-pane fade", id = "lme4-correlations", role = "tabpanel",
div(
class = "section",
h2("🔗 Trait Correlations"),
div(
id = "lme4_correlations_content",
div(class = "chart-container", plotlyOutput("lme4_correlation_plot", height = "600px")),
div(class = "table-container", DTOutput("lme4_cor_table")),
div(
class = "insights",
h4("💡 Interpretation"),
p("Correlations reveal trait synergies or trade-offs. Positive correlations (near 1) suggest traits improve together; negative correlations (near -1) indicate trade-offs.")
)
),
div(
id = "lme4_correlations_placeholder", class = "text-center",
icon("link", class = "fas", style = "font-size: 72px; color: var(--light); margin: 30px 0;"),
h4("📤 Upload data to see trait correlations", style = "color: var(--light);")
)
)
)
)
)
)
)
# Server function
server <- function(input, output, session) {
# LME4 Analysis Reactive Values
rv_lme4 <- reactiveValues(
data = NULL,
traits = NULL,
trait = NULL,
lme4_models = NULL,
blues_all = NULL,
cor_matrix = NULL,
cor_table = NULL,
descriptives = NULL,
debug_log = NULL,
plot_colors = list(
primary = "#1E3A8A",
secondary = "#6B8E23",
accent = "#4169E1",
highlight = "#FF8C00"
)
)
# Update colors when apply button is clicked
observeEvent(input$apply_colors, {
rv_lme4$plot_colors$primary <- input$color_primary
rv_lme4$plot_colors$secondary <- input$color_secondary
rv_lme4$plot_colors$accent <- input$color_accent
rv_lme4$plot_colors$highlight <- input$color_highlight
showNotification("Colors updated! Refresh plots to see changes.", type = "message")
})
# Generate color palette based on selected colors
get_color_palette <- function() {
c(
rv_lme4$plot_colors$primary,
rv_lme4$plot_colors$secondary,
rv_lme4$plot_colors$accent,
rv_lme4$plot_colors$highlight,
"#B5EAD7", "#E6E6FA", "#FFFACD", "#FF9999"
)
}
# Plot formatting with dynamic colors
get_plot_layout <- function() {
list(
plot_bgcolor = "transparent",
paper_bgcolor = "transparent",
margin = list(l = 80, r = 80, t = 100, b = 100),
font = list(family = "Poppins", size = 14, color = "#2D3748"),
showlegend = TRUE,
legend = list(orientation = "h", y = -0.2, x = 0.5, xanchor = "center")
)
}
# LME4: Process data
lme4_process_data <- function(path) {
message("LME4: Reading Excel file: ", path)
tryCatch({
data <- read_excel(path)
colnames(data) <- make.names(colnames(data), unique = TRUE)
required_cols <- c("Genotype", "Block", "Row", "Column", "Rep", "Environment")
missing_cols <- setdiff(required_cols, names(data))
if (length(missing_cols) > 0) {
stop("Missing required columns: ", paste(missing_cols, collapse = ", "))
}
data$Genotype <- as.factor(data$Genotype)
data$Block <- as.factor(data$Block)
data$Row <- as.factor(data$Row)
data$Rep <- as.factor(data$Rep)
data$Column <- as.factor(data$Column)
data$Environment <- as.factor(data$Environment)
data$Environment <- factor(data$Environment, levels = unique(data$Environment))
all_cols <- names(data)
trait_cols <- all_cols[9:length(all_cols)]
numeric_cols <- trait_cols[sapply(data[trait_cols], is.numeric)]
if (length(numeric_cols) == 0) {
stop("No numeric columns found for traits starting from column 9")
}
n_genotypes <- length(unique(data$Genotype))
n_environments <- length(unique(data$Environment))
if (n_genotypes < 3) {
stop("Insufficient genotypes (", n_genotypes, ") for LME4 analysis; need at least 3")
}
if (n_environments < 2) {
stop("Insufficient environments (", n_environments, ") for LME4 analysis; need at least 2")
}
combo_counts <- table(data$Environment, data$Genotype)
zero_combinations <- sum(combo_counts == 0)
if (zero_combinations > 0) {
message("LME4: Warning: ", zero_combinations, " Environment:Genotype combinations have no data")
}
if (zero_combinations > (nrow(combo_counts) * ncol(combo_counts) * 0.5)) {
showNotification("Warning: Over 50% of Environment:Genotype combinations are missing", type = "warning", duration = 10)
}
missing_data <- data %>%
group_by(Environment) %>%
summarise(across(all_of(numeric_cols), ~ sum(is.na(.)) / length(.)))
bad_envs <- missing_data %>%
pivot_longer(cols = all_of(numeric_cols), names_to = "Trait", values_to = "Missing") %>%
filter(Missing > 0.2) %>%
pull(Environment) %>%
unique()
if (length(bad_envs) > 0) {
message("LME4: Filtering out environments with >20% missing data: ", paste(bad_envs, collapse = ", "))
data <- data %>% filter(!Environment %in% bad_envs) %>% droplevels()
}
message("LME4: Data summary: Rows=", nrow(data), ", Genotypes=", n_genotypes, ", Environments=", n_environments, ", Traits=", paste(numeric_cols, collapse = ", "))
return(list(data = data, traits = numeric_cols))
}, error = function(e) {
message("LME4: Error in data processing: ", e$message)
showNotification(paste("Error processing file:", e$message), type = "error", duration = 10)
return(NULL)
})
}
# LME4: Fit model
lme4_fit_model <- function(data, trait) {
message("LME4: Fitting model for ", trait)
formula_str <- if (input$lme4_include_interaction) {
paste(trait, "~ Environment + Genotype + Environment:Genotype + (1|Block) + (1|Row) + (1|Column) + (1|Rep)")
} else {
paste(trait, "~ Environment + Genotype + (1|Block) + (1|Row) + (1|Column) + (1|Rep)")
}
formula <- as.formula(formula_str)
tryCatch({
model <- lmer(formula, data = data, na.action = na.omit,
control = lmerControl(check.rankX = "warn+drop.cols", optimizer = "bobyqa"))
message("LME4: Successfully fitted model for ", trait)
return(model)
}, error = function(e) {
message("LME4: Error fitting model for ", trait, ": ", e$message)
showNotification(paste("Model fitting failed for", trait, ": ", e$message), type = "error", duration = 10)
return(NULL)
}, warning = function(w) {
message("LME4: Warning in model fitting for ", trait, ": ", w$message)
showNotification(paste("Warning for", trait, ": ", w$message), type = "warning", duration = 10)
return(NULL)
})
}
# LME4: Get BLUEs
lme4_get_blue <- function(model, trait) {
if (is.null(model)) {
message("LME4: No model for ", trait)
return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, Error = "No model fitted"))
}
tryCatch({
emm_options(pbkrtest.limit = 5000, lmerTest.limit = 5000)
blues <- emmeans(model, ~ Genotype:Environment)
blues_df <- as.data.frame(blues) %>%
rename(predicted.value = emmean) %>%
mutate(Trait = trait) %>%
select(Trait, Genotype, Environment, predicted.value, SE = SE) %>%
filter(!is.na(predicted.value))
if (nrow(blues_df) == 0) {
return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, SE = NA, Error = "No valid BLUEs"))
}
return(blues_df)
}, error = function(e) {
message("LME4: Error in BLUEs for ", trait, ": ", e$message)
return(data.frame(Trait = trait, Genotype = NA, Environment = NA, predicted.value = NA, SE = NA, Error = e$message))
})
}
# LME4: File upload observer
observeEvent(input$lme4_file, {
req(input$lme4_file)
message("LME4: File upload triggered: ", input$lme4_file$name)
shinyjs::show("lme4_loader")
on.exit(shinyjs::hide("lme4_loader"))
result <- lme4_process_data(input$lme4_file$datapath)
if (is.null(result)) {
return()
}
rv_lme4$data <- result$data
rv_lme4$traits <- result$traits
rv_lme4$trait <- result$traits[1]
updateSelectInput(session, "lme4_selected_trait", choices = rv_lme4$traits, selected = rv_lme4$traits[1])
shinyjs::show("lme4_data_stats")
output$lme4_n_vars <- renderText({ ncol(rv_lme4$data) })
output$lme4_n_obs <- renderText({ nrow(rv_lme4$data) })
output$lme4_n_geno <- renderText({ length(unique(rv_lme4$data$Genotype)) })
output$lme4_n_env <- renderText({ length(unique(rv_lme4$data$Environment)) })
output$lme4_data_preview <- renderPrint({
str(rv_lme4$data)
})
debug_log <- c()
withProgress(message = 'LME4: Analyzing data', value = 0, {
lme4_models <- list()
blues_list <- list()
total_steps <- length(rv_lme4$traits) * 2 + 2
step_increment <- 1 / total_steps
for (trait in rv_lme4$traits) {
incProgress(step_increment, detail = paste("Fitting model for", trait))
model <- lme4_fit_model(rv_lme4$data, trait)
lme4_models[[trait]] <- model
debug_log <- c(debug_log, paste("Trait:", trait, "- Model fitted:", ifelse(is.null(model), "Failed", "Success")))
incProgress(step_increment, detail = paste("Calculating predicted means for", trait))
blues_list[[trait]] <- lme4_get_blue(model, trait)
}
incProgress(step_increment, detail = "Calculating correlations")
if (length(rv_lme4$traits) > 1) {
trait_data <- rv_lme4$data %>% select(all_of(rv_lme4$traits)) %>% na.omit()
if (nrow(trait_data) > 0) {
cor_matrix <- cor(trait_data, use = "pairwise.complete.obs")
cor_table <- as.data.frame(as.table(cor_matrix)) %>%
rename(Trait1 = Var1, Trait2 = Var2, Correlation = Freq) %>%
mutate(Correlation = round(Correlation, 3))
rv_lme4$cor_matrix <- cor_matrix
rv_lme4$cor_table <- cor_table
debug_log <- c(debug_log, "Correlations: Success")
} else {
rv_lme4$cor_matrix <- matrix(NA, nrow = 1, ncol = 1, dimnames = list("NoData", "NoData"))
rv_lme4$cor_table <- data.frame(Trait1 = "NoData", Trait2 = "NoData", Correlation = NA)
debug_log <- c(debug_log, "Correlations: No valid data")
}
} else {
rv_lme4$cor_matrix <- matrix(1, nrow = 1, ncol = 1, dimnames = list(rv_lme4$traits, rv_lme4$traits))
rv_lme4$cor_table <- data.frame(Trait1 = rv_lme4$traits, Trait2 = rv_lme4$traits, Correlation = 1)
debug_log <- c(debug_log, "Correlations: Single trait")
}
incProgress(step_increment, detail = "Calculating descriptive statistics")
descriptives <- rv_lme4$data %>%
select(all_of(rv_lme4$traits)) %>%
pivot_longer(cols = everything(), names_to = "Trait", values_to = "Value") %>%
group_by(Trait) %>%
summarise(
Mean = mean(Value, na.rm = TRUE),
SD = sd(Value, na.rm = TRUE),
Min = min(Value, na.rm = TRUE),
Max = max(Value, na.rm = TRUE),
N = sum(!is.na(Value)),
.groups = "drop"
) %>%
mutate(CV = round((SD / Mean) * 100, 2))
rv_lme4$descriptives <- descriptives
debug_log <- c(debug_log, "Descriptives: Success")
rv_lme4$lme4_models <- lme4_models
rv_lme4$blues_all <- bind_rows(blues_list) %>% filter(!is.na(predicted.value))
rv_lme4$debug_log <- debug_log
shinyjs::hide("lme4_blues_placeholder")
shinyjs::show("lme4_blues_content")
shinyjs::hide("lme4_correlations_placeholder")
shinyjs::show("lme4_correlations_content")
shinyjs::hide("lme4_descriptives_placeholder")
shinyjs::show("lme4_descriptives_content")
output$lme4_debug_log <- renderPrint({
cat(paste(rv_lme4$debug_log, collapse = "\n"))
})
showNotification("LME4: File uploaded and analyzed successfully", type = "message", duration = 5)
})
})
# Update selected trait
observe({
req(input$lme4_selected_trait)
rv_lme4$trait <- input$lme4_selected_trait
})
# LME4: Filtered reactives
lme4_filtered_blues <- reactive({
req(rv_lme4$blues_all, rv_lme4$trait)
rv_lme4$blues_all %>% filter(Trait == rv_lme4$trait, !is.na(predicted.value))
})
# LME4: Plot outputs
output$lme4_blues_plot <- renderPlotly({
req(lme4_filtered_blues())
data <- lme4_filtered_blues()
if (nrow(data) == 0 || all(is.na(data$predicted.value))) {
return(plot_ly() %>%
layout(
title = list(text = paste("No Valid Predicted Means for", rv_lme4$trait), font = list(family = "Poppins")),
annotations = list(
text = "No valid data for plotting predicted means.",
x = 0.5, y = 0.5, xref = "paper", yref = "paper",
showarrow = FALSE, font = list(size = 12, color = "#2D3748")
),
get_plot_layout()
))
}
plot_ly(data, x = ~Environment, y = ~predicted.value, color = ~Genotype,
type = 'scatter', mode = 'lines+markers',
marker = list(size = 8),
line = list(width = 2),
colors = get_color_palette(),
text = ~paste("Genotype:", Genotype, "<br>Value:", round(predicted.value, 2)),
hoverinfo = "text") %>%
layout(
title = list(text = paste("Predicted Means (BLUEs) for", rv_lme4$trait), font = list(size = 18, family = "Poppins", color = "#2D3748")),
xaxis = list(title = "Environment", tickangle = 45, titlefont = list(family = "Poppins"), tickfont = list(family = "Poppins")),
yaxis = list(title = "Predicted Value", titlefont = list(family = "Poppins"), tickfont = list(family = "Poppins")),
get_plot_layout(),
hoverlabel = list(bgcolor = "white", font = list(family = "Poppins"))
)
})
# Scatter plot matrix for correlations
output$lme4_correlation_plot <- renderPlotly({
req(rv_lme4$data, rv_lme4$traits)
if (length(rv_lme4$traits) < 2) {
return(plot_ly() %>%
layout(
title = list(text = "Need at least 2 traits for correlation plot", font = list(family = "Poppins")),
annotations = list(
text = "Upload data with at least 2 numeric traits.",
x = 0.5, y = 0.5, xref = "paper", yref = "paper",
showarrow = FALSE, font = list(size = 12, color = "#2D3748")
),
get_plot_layout()
))
}
# Prepare data for scatter plot matrix
plot_data <- rv_lme4$data %>%
select(all_of(rv_lme4$traits)) %>%
na.omit()
if (nrow(plot_data) == 0) {
return(plot_ly() %>%
layout(
title = list(text = "No valid data for correlation plot", font = list(family = "Poppins")),
annotations = list(
text = "No complete cases found for the selected traits.",
x = 0.5, y = 0.5, xref = "paper", yref = "paper",
showarrow = FALSE, font = list(size = 12, color = "#2D3748")
),
get_plot_layout()
))
}
# Create scatter plot matrix
fig <- plot_ly(type = 'splom', dimensions = lapply(names(plot_data), function(col) {
list(label = col, values = plot_data[[col]])
}))
fig <- fig %>% layout(
title = list(text = "Trait Correlation Scatter Plot Matrix", font = list(size = 18, family = "Poppins", color = "#2D3748")),
dragmode = 'select',
hovermode = 'closest',
plot_bgcolor = 'transparent',
paper_bgcolor = 'transparent',
font = list(family = "Poppins", size = 12)
)
fig
})
# LME4: Descriptive Statistics Plot (Boxplot by Environment for selected trait)
output$lme4_descriptives_plot <- renderPlotly({
req(rv_lme4$data, rv_lme4$trait)
trait_data <- rv_lme4$data[[rv_lme4$trait]]
if (all(is.na(trait_data)) || length(unique(rv_lme4$data$Environment)) < 2) {
return(plot_ly() %>%
layout(
title = list(text = paste("No Valid Data for", rv_lme4$trait), font = list(family = "Poppins")),
annotations = list(
text = "No valid data for boxplot.",
x = 0.5, y = 0.5, xref = "paper", yref = "paper",
showarrow = FALSE, font = list(size = 12, color = "#2D3748")
),
get_plot_layout()
))
}
plot_ly(rv_lme4$data, x = ~Environment, y = rv_lme4$data[[rv_lme4$trait]], type = 'box',
color = ~Environment, colors = get_color_palette(),
hoverinfo = "y+name") %>%
layout(
title = list(text = paste("Distribution of", rv_lme4$trait, "by Environment"), font = list(size = 18, family = "Poppins", color = "#2D3748")),
xaxis = list(title = "Environment", titlefont = list(family = "Poppins"), tickfont = list(family = "Poppins")),
yaxis = list(title = paste(rv_lme4$trait, "Value"), titlefont = list(family = "Poppins"), tickfont = list(family = "Poppins")),
get_plot_layout(),
hoverlabel = list(bgcolor = "white", font = list(family = "Poppins"))
)
})
# LME4: Table outputs
output$lme4_blues_table <- renderDT({
req(lme4_filtered_blues())
datatable(
lme4_filtered_blues() %>% select(-Error),
extensions = 'Buttons',
options = list(
scrollX = TRUE,
dom = 'Bfrtip',
buttons = c('copy', 'excel', 'pdf', 'print'),
pageLength = 10,
columnDefs = list(list(className = 'dt-center', targets = '_all'))
),
caption = paste("Predicted Means (BLUEs) for", rv_lme4$trait)
) %>% formatRound(columns = c("predicted.value", "SE"), digits = 3)
})
output$lme4_cor_table <- renderDT({
req(rv_lme4$cor_table)
datatable(
rv_lme4$cor_table,
extensions = 'Buttons',
options = list(
scrollX = TRUE,
dom = 'Bfrtip',
buttons = c('copy', 'excel', 'pdf', 'print'),
pageLength = 10,
columnDefs = list(list(className = 'dt-center', targets = '_all'))
),
caption = "Correlation Between Traits"
) %>% formatRound(columns = "Correlation", digits = 3)
})
output$lme4_descriptives_table <- renderDT({
req(rv_lme4$descriptives)
datatable(
rv_lme4$descriptives,
extensions = 'Buttons',
options = list(
scrollX = TRUE,
dom = 'Bfrtip',
buttons = c('copy', 'excel', 'pdf', 'print'),
pageLength = 10,
columnDefs = list(list(className = 'dt-center', targets = c(2:6)))
),
caption = "Descriptive Statistics for Traits"
) %>% formatRound(columns = c("Mean", "SD", "Min", "Max", "CV"), digits = 2)
})
}
# Run the Shiny app
shinyApp(ui, server)