You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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 the observe() 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's req() 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

  1. 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.
  2. Reactive Value: fetched_data <- reactiveVal(NULL) creates a reactive container to store our data, making it accessible to output functions.
  3. Input Validation: req(input$metadata) stops the observe block from running until the user enters text, avoiding unnecessary API calls.
  4. 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.
  5. Output Elements: We added tableOutput to show the data and textOutput to display errors. The renderTable function converts the time series object to a data frame for proper display.

Optional Improvements

  • Use selectInput Instead of textInput: 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 shinycssloaders package 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_date and end_date parameters).

内容的提问来源于stack exchange,提问作者Bhavana bharti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:57:33