shiny app not opening my excel file?

,

My shiny app gives this warning

" Warning in file(file, "rt") :
2024-11-07T10:47:19.718802+00:00 shinyapps[13262355]:   cannot open file 'Cancer_Data.csv': No such file or directory
2024-11-07T10:47:19.722822+00:00 shinyapps[13262355]: Warning: Error in file: cannot open the connection
2024-11-07T10:47:19.727138+00:00 shinyapps[13262355]:   203: file"

my file has xlsx file and it normally opens. This problem never resolve . Why?

Does this happen when running the app locally (say in RStudio) or only when running it on a server? Can you post a minimal example (a reprex) that encounters the problem?

This is my code.:

# Load required libraries
library(shiny)
library(shinydashboard)
library(ggplot2)
library(caret)
library(glmnet)
library(pROC)
library(conflicted)
library(readxl)
library(rsconnect)

# Set preference for shinydashboard::box to avoid conflict
conflicts_prefer(shinydashboard::box)


Cancer_Data <- read_excel("C:/Users/NITRO 5/OneDrive/Documents/Cancer _predict/Cancer_Data.xlsx")


# UI layout
ui <- dashboardPage(
  dashboardHeader(title = "Cancer Diagnosis Prediction"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Model Performance", tabName = "performance", icon = icon("chart-line")),
      menuItem("Prediction", tabName = "prediction", icon = icon("diagnoses"))
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(
        tabName = "performance",
        fluidRow(
          shinydashboard::box(plotOutput("rocPlot"), title = "ROC Curve"),
          shinydashboard::box(tableOutput("metricsTable"), title = "Model Metrics")
        )
      ),
      tabItem(
        tabName = "prediction",
        fluidRow(
          shinydashboard::box(
            title = "Enter Predictor Values",
            # Add inputs for each predictor variable
            uiOutput("inputFields"),
            actionButton("predictBtn", "Predict Diagnosis")
          ),
          shinydashboard::box(
            title = "Prediction Result",
            textOutput("predictionResult")
          )
        )
      )
    )
  )
)

# Server logic
server <- function(input, output, session) {
  
  # Preprocess data
  train_data <- reactive({
    req(Cancer_Data) # Ensure Cancer_Data is loaded
    set.seed(125)
    trainIndex <- createDataPartition(Cancer_Data$diagnosis, p = 0.75, list = FALSE)
    train_data <- Cancer_Data[trainIndex, ]
    train_data <- na.omit(train_data)
    train_data$diagnosis <- as.factor(train_data$diagnosis)
    return(train_data)
  })
  
  # Train models
  fit_glm <- reactive({
    req(train_data()) # Ensure train_data is available
    train(diagnosis ~ ., data = train_data(), method = "glm", 
          metric = "ROC", preProc = c("center", "scale"),
          trControl = trainControl(method = "cv", classProbs = TRUE, summaryFunction = twoClassSummary))
  })
  
  fit_glmnet <- reactive({
    req(train_data()) # Ensure train_data is available
    train(diagnosis ~ ., data = train_data(), method = "glmnet", 
          metric = "ROC", preProc = c("center", "scale"),
          trControl = trainControl(method = "cv", classProbs = TRUE, summaryFunction = twoClassSummary))
  })
  
  # Plot ROC Curve
  output$rocPlot <- renderPlot({
    req(fit_glm(), fit_glmnet()) # Ensure models are trained
    glm_roc <- roc(response = train_data()$diagnosis, predictor = predict(fit_glm(), train_data(), type = "prob")[,2])
    glmnet_roc <- roc(response = train_data()$diagnosis, predictor = predict(fit_glmnet(), train_data(), type = "prob")[,2])
    plot(glm_roc, col = "blue", main = "ROC Curves for Models")
    lines(glmnet_roc, col = "red")
    legend("bottomright", legend = c("GLM", "GLMNET"), col = c("blue", "red"), lty = 1)
  })
  
  # Display Sensitivity and Specificity
  output$metricsTable <- renderTable({
    req(fit_glm(), fit_glmnet()) # Ensure models are trained
    glm_conf <- confusionMatrix(predict(fit_glm(), train_data()), train_data()$diagnosis)
    glmnet_conf <- confusionMatrix(predict(fit_glmnet(), train_data()), train_data()$diagnosis)
    
    data.frame(
      Model = c("GLM", "GLMNET"),
      Sensitivity = c(glm_conf$byClass["Sensitivity"], glmnet_conf$byClass["Sensitivity"]),
      Specificity = c(glm_conf$byClass["Specificity"], glmnet_conf$byClass["Specificity"])
    )
  })
  
  # Generate input fields for predictors in Tab 2
  output$inputFields <- renderUI({
    req(train_data()) # Ensure train_data is available
    input_list <- lapply(names(train_data())[-which(names(train_data()) == "diagnosis")], function(var) {
      numericInput(inputId = var, label = var, value = 0)
    })
    do.call(tagList, input_list)
  })
  
  # Prediction based on user input
  output$predictionResult <- renderText({
    req(input$predictBtn)
    req(fit_glmnet()) # Ensure model is trained
    
    # Gather input data for prediction
    input_data <- as.data.frame(t(sapply(names(train_data())[-which(names(train_data()) == "diagnosis")], 
                                         function(var) input[[var]])))
    colnames(input_data) <- names(train_data())[-which(names(train_data()) == "diagnosis")]
    
    # Predict diagnosis
    prediction <- predict(fit_glmnet(), input_data)
    paste("Predicted Diagnosis:", prediction)
  })
}

# Run the app
shinyApp(ui, server)

Example data:

cancer_data <- data.frame(
  diagnosis = c("M", "M", "M", "B", "B"),
  radius_mean = c(17.99, 20.57, 19.69, 11.42, 13.85),
  texture_mean = c(10.38, 17.77, 21.25, 20.38, 16.54),
  perimeter_mean = c(122.8, 132.9, 130.0, 77.58, 86.49),
  area_mean = c(1001, 1326, 1203, 386.1, 403.5),
  smoothness_mean = c(0.1184, 0.08474, 0.1096, 0.1425, 0.1003),
  compactness_mean = c(0.2776, 0.07864, 0.1599, 0.2839, 0.1328)
)

Dont use absolute path to the excel. If the excel is in your project/work directory, then you can refer to it relatively, just with the file name alone.

When you app is deployed on a foreign server it wont have your c:/Users pathz but it will have put project materials somewhere, and thats all you need.

setwd("C:\Users\NITRO 5\OneDrive\Documents\Cancer _predict")
runApp('~')
[conflicted] Removing existing preference.
[conflicted] Will prefer shinydashboard::box over any other package.
Error: path does not exist: ‘Cancer_Data.xlsx’

Where is your app.R file?

I have put the app.R's code here:

# Load required libraries
library(shiny)
library(shinydashboard)
library(ggplot2)
library(caret)
library(glmnet)
library(pROC)
library(conflicted)
library(readxl)
library(rsconnect)

# Set preference for shinydashboard::box to avoid conflict
conflicts_prefer(shinydashboard::box)


Cancer_Data <- read_excel("Cancer_Data.xlsx")


# UI layout
ui <- dashboardPage(
  dashboardHeader(title = "Cancer Diagnosis Prediction"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Model Performance", tabName = "performance", icon = icon("chart-line")),
      menuItem("Prediction", tabName = "prediction", icon = icon("diagnoses"))
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(
        tabName = "performance",
        fluidRow(
          shinydashboard::box(plotOutput("rocPlot"), title = "ROC Curve"),
          shinydashboard::box(tableOutput("metricsTable"), title = "Model Metrics")
        )
      ),
      tabItem(
        tabName = "prediction",
        fluidRow(
          shinydashboard::box(
            title = "Enter Predictor Values",
            # Add inputs for each predictor variable
            uiOutput("inputFields"),
            actionButton("predictBtn", "Predict Diagnosis")
          ),
          shinydashboard::box(
            title = "Prediction Result",
            textOutput("predictionResult")
          )
        )
      )
    )
  )
)

# Server logic
server <- function(input, output, session) {
  
  # Preprocess data
  train_data <- reactive({
    req(Cancer_Data) # Ensure Cancer_Data is loaded
    set.seed(125)
    trainIndex <- createDataPartition(Cancer_Data$diagnosis, p = 0.75, list = FALSE)
    train_data <- Cancer_Data[trainIndex, ]
    train_data <- na.omit(train_data)
    train_data$diagnosis <- as.factor(train_data$diagnosis)
    return(train_data)
  })
  
  # Train models
  fit_glm <- reactive({
    req(train_data()) # Ensure train_data is available
    train(diagnosis ~ ., data = train_data(), method = "glm", 
          metric = "ROC", preProc = c("center", "scale"),
          trControl = trainControl(method = "cv", classProbs = TRUE, summaryFunction = twoClassSummary))
  })
  
  fit_glmnet <- reactive({
    req(train_data()) # Ensure train_data is available
    train(diagnosis ~ ., data = train_data(), method = "glmnet", 
          metric = "ROC", preProc = c("center", "scale"),
          trControl = trainControl(method = "cv", classProbs = TRUE, summaryFunction = twoClassSummary))
  })
  
  # Plot ROC Curve
  output$rocPlot <- renderPlot({
    req(fit_glm(), fit_glmnet()) # Ensure models are trained
    glm_roc <- roc(response = train_data()$diagnosis, predictor = predict(fit_glm(), train_data(), type = "prob")[,2])
    glmnet_roc <- roc(response = train_data()$diagnosis, predictor = predict(fit_glmnet(), train_data(), type = "prob")[,2])
    plot(glm_roc, col = "blue", main = "ROC Curves for Models")
    lines(glmnet_roc, col = "red")
    legend("bottomright", legend = c("GLM", "GLMNET"), col = c("blue", "red"), lty = 1)
  })
  
  # Display Sensitivity and Specificity
  output$metricsTable <- renderTable({
    req(fit_glm(), fit_glmnet()) # Ensure models are trained
    glm_conf <- confusionMatrix(predict(fit_glm(), train_data()), train_data()$diagnosis)
    glmnet_conf <- confusionMatrix(predict(fit_glmnet(), train_data()), train_data()$diagnosis)
    
    data.frame(
      Model = c("GLM", "GLMNET"),
      Sensitivity = c(glm_conf$byClass["Sensitivity"], glmnet_conf$byClass["Sensitivity"]),
      Specificity = c(glm_conf$byClass["Specificity"], glmnet_conf$byClass["Specificity"])
    )
  })
  
  # Generate input fields for predictors in Tab 2
  output$inputFields <- renderUI({
    req(train_data()) # Ensure train_data is available
    input_list <- lapply(names(train_data())[-which(names(train_data()) == "diagnosis")], function(var) {
      numericInput(inputId = var, label = var, value = 0)
    })
    do.call(tagList, input_list)
  })
  
  # Prediction based on user input
  output$predictionResult <- renderText({
    req(input$predictBtn)
    req(fit_glmnet()) # Ensure model is trained
    
    # Gather input data for prediction
    input_data <- as.data.frame(t(sapply(names(train_data())[-which(names(train_data()) == "diagnosis")], 
                                         function(var) input[[var]])))
    colnames(input_data) <- names(train_data())[-which(names(train_data()) == "diagnosis")]
    
    # Predict diagnosis
    prediction <- predict(fit_glmnet(), input_data)
    paste("Predicted Diagnosis:", prediction)
  })
}

# Run the app
shinyApp(ui, server)

The important part is where is it ? The path of it

in the same place with the excel

both of the excel file and the app is in the working directory within same folder

I dont understand this :

> runApp('~')

because on windows that tilde shouldnt really mean anything

Error in `shinyAppDir()`:
! App dir must contain either app.R or server.R.

but somehow you were able to run the app.R and for the R session processing that app.R to not have access to other files in that same folder.