如何在Shiny应用中读取Dropbox大TXT文件并替代Iris数据集?
Modified Shiny Code to Read Dropbox TXT File
First, here's the updated code that swaps the Iris dataset with your Dropbox TXT file. The key tweak here is using the raw download URL (changing dl=0 to dl=1) so R can read the file directly instead of loading the Dropbox preview page:
library(shiny) library(shinydashboard) library(DT) # Ensure this package is installed/loaded for interactive tables # Load the Dropbox TXT file once when the app starts (better for large files) # Adjust sep, header, and other parameters to match your file's structure my_data <- read.table( url("https://www.dropbox.com/s/k94brqtrp5thch3/005.txt?dl=1"), header = TRUE, # Set to FALSE if your file has no column headers sep = "\t", # Swap to "," for CSV-style TXT, " " for space-separated, etc. stringsAsFactors = FALSE ) ui <- dashboardPage( dashboardHeader(), dashboardSidebar(), dashboardBody( fluidRow( tabBox(width = 12, height = NULL, tabPanel("Data", value=2, fluidRow( column(width = 4, box(title = "My TXT Data", width = NULL, solidHeader = FALSE, dataTableOutput("dat1")) ) ) ) ) ) ) ) server <- function(input, output) { output$dat1 <- renderDataTable({ datatable(my_data) }) } shinyApp(ui, server)
Key Changes Explained:
- Raw URL Adjustment: Changing
dl=0todl=1bypasses Dropbox's preview and serves the raw file content. - File Reading:
read.table()loads the data—tweaksepandheaderto match how your TXT file is formatted (e.g., usesep=","if it’s a CSV saved as TXT). - Performance: Loading the file outside the server function ensures it’s only read once when the app starts, which is much more efficient for large datasets.
Rendering a Basic HTML Table Instead of Interactive DataTable
If you want a simple static HTML table (no sorting, searching, or pagination), replace the dataTableOutput/renderDataTable pair with tableOutput/renderTable:
library(shiny) library(shinydashboard) # Same data loading code as above my_data <- read.table( url("https://www.dropbox.com/s/k94brqtrp5thch3/005.txt?dl=1"), header = TRUE, sep = "\t", stringsAsFactors = FALSE ) ui <- dashboardPage( dashboardHeader(), dashboardSidebar(), dashboardBody( fluidRow( tabBox(width = 12, height = NULL, tabPanel("Data", value=2, fluidRow( column(width = 4, box(title = "My TXT Data (HTML Table)", width = NULL, solidHeader = FALSE, tableOutput("dat1")) # Replaced dataTableOutput ) ) ) ) ) ) ) server <- function(input, output) { output$dat1 <- renderTable({ # Replaced renderDataTable my_data }) } shinyApp(ui, server)
What’s Different:
- UI Element:
tableOutputrenders a plain HTML table instead of the interactive DT widget. - Server Logic:
renderTabletakes the raw data frame directly (no need fordatatable()wrapper). - Result: A clean, static table perfect for straightforward data display without extra interactivity.
内容的提问来源于stack exchange,提问作者fi1d18




