如何在R Shiny中从Quandl动态提取数据?代码报错求助
Fixing Dynamic Quandl Data Extraction in R Shiny
Let's walk through fixing your code step by step. First, let's identify the key issues in your original implementation, then share a corrected version with explanations.
Key Issues in Your Original Code
- API Key Placement: Setting
Quandl.api_key()inside theobserve()block runs it every time the input changes, which is unnecessary—this only needs to be set once when your app starts. - No Reactive Storage: You're fetching data but not storing it in a reactive value, so there's no way to use this data in outputs (like tables or plots).
- Lack of Error Handling: If the user enters an invalid company ticker, Quandl will throw an error that crashes your app.
- Input Validation: Using
is.null(input$metadata)works, but Shiny'sreq()function is a cleaner, more idiomatic way to handle required inputs. - Missing Output: There's no element to display the fetched data, so you won't see the results even if the code works.
Corrected Code
Here's a working version that addresses all these issues:
library(shiny) library(Quandl) # Set API key once at app startup Quandl.api_key("qZAzm6zea4nVK69ztzDJ") ui <- fluidPage( titlePanel("Quandl Company Data Extractor"), sidebarLayout( sidebarPanel( textInput( inputId = "metadata", label = "Enter NSE Company Ticker (e.g., TCS)", placeholder = "TCS" ) ), mainPanel( tableOutput("company_data"), textOutput("error_message") ) ) ) server <- function(input, output) { # Reactive value to store fetched data fetched_data <- reactiveVal(NULL) observe({ # Require input to be non-empty before proceeding req(input$metadata) # Clean up the input (remove whitespace, uppercase) company_ticker <- toupper(trimws(input$metadata)) quandl_code <- paste0("NSE/", company_ticker) # Fetch data with error handling tryCatch({ data <- Quandl(quandl_code, type = "ts") fetched_data(data) output$error_message <- renderText("") # Clear error if successful }, error = function(e) { fetched_data(NULL) # Reset data on error output$error_message <- renderText(paste("Error:", e$message)) }) }) # Render the fetched data as a table output$company_data <- renderTable({ req(fetched_data()) # Only render if data exists # Convert time series to data frame for table display as.data.frame(fetched_data()) }) } shinyApp(ui = ui, server = server)
Key Fixes Explained
- API Key Setup: We set
Quandl.api_key()outside the server function so it runs once when the app starts, not on every input change. - Reactive Value:
fetched_data <- reactiveVal(NULL)creates a reactive container to store our data, making it accessible to output functions. - Input Validation:
req(input$metadata)stops the observe block from running until the user enters text, avoiding unnecessary API calls. - Error Handling:
tryCatch()wraps the Quandl call to catch invalid tickers or API issues, displaying a user-friendly error message instead of crashing the app. - Output Elements: We added
tableOutputto show the data andtextOutputto display errors. TherenderTablefunction converts the time series object to a data frame for proper display.
Optional Improvements
- Use
selectInputInstead oftextInput: If you know the list of valid NSE tickers, a dropdown menu will prevent typos. For example:selectInput( inputId = "metadata", label = "Select Company", choices = c("TCS", "INFY", "RELIANCE") ) - Add Loading Spinner: Use the
shinycssloaderspackage to show a spinner while data is being fetched. - Limit Data Range: Add date inputs to let users specify a time range for the data (Quandl supports
start_dateandend_dateparameters).
内容的提问来源于stack exchange,提问作者Bhavana bharti
相关产品推荐
相关产品推荐

