[英]R ShinyDashboard. Retriving data via API into a data frame after ActionButton. Function error
我正在尝试创建一个简单的应用程序,以根据公司的 CVR(识别号)获取公司的基本信息。 例如,通过输入 LEGO 的 CVR 编号 (54562519) 并按下“搜索”按钮,API 将查找它并生成一个表格。 这是我的示例代码:
使用 '54562519' cvr 输入来测试它。 API 代码在 shiny 应用程序之外工作。
library(shiny)
library(shinydashboard)
library(httr)
library(jsonlite)
library(dplyr)
header <- dashboardHeader()
sidebar <- dashboardSidebar(sidebarMenu(
menuItem("New Entry",tabName = "new_entry_tab", icon = icon("stats-bars", lib = 'glyphicon'))))
body <- dashboardBody(
tabItems(
tabItem(tabName = "new_entry_tab",
fluidPage(
fluidRow(numericInput(inputId = "cvr", "Enter CVR number:",
value = "cvr",
min = 1000000,
max = 9999999,
step = NA,
width = NULL)),
fluidRow(actionButton("button_cvr", "Search")),
fluidRow(box(tableOutput("firm_info")))
))))
ui <- dashboardPage(header, sidebar, body)
# Server ----
server <- function(input, output) {
api_firm_call <- observeEvent(input$button_cvr, {
cvr <- input$cvr
firm_data <- GET(paste0("https://cvrapi.dk/api?search=",cvr,"&country=dk"))
firm <-fromJSON(rawToChar(firm_data$content))
firm_matrix <- matrix(ncol = 1, nrow = 5)
rownames(firm_matrix) <- c("Name", "Address", "City", "Industry", "Industry Name")
colnames(firm_matrix) <- " "
firm_matrix[1:5, 1] <- c(firm$name, firm$address, paste(firm$zipcode, firm$city),firm$industrycode, firm$industrydesc)
firm_table <- tibble(firm_matrix)
})
output$firm_info <- renderTable({api_firm_call()})
}
shinyApp(ui, server)
我收到警告:api_firm_call 中的错误:找不到 function “api_firm_call”,但我不知道如何处理。
而不是使用observeEvent
切换到eventReactive
来解决您的问题,因为它允许返回您的firm_table
。 此外,我将您的 API 搜索代码移到了单独的 function 中。 这样做会使您的代码更易于调试,即您可以在 shiny 之外测试 function,并使您的代码更干净。
注意:为了使 reprex 更小,我删除了numericInput
并对cvr
示例值进行了硬编码:
library(shiny)
library(shinydashboard)
library(httr)
library(jsonlite)
library(dplyr)
fct_api_firm_call <- function(cvr) {
firm_data <- GET(paste0("https://cvrapi.dk/api?search=",cvr,"&country=dk"))
firm <-fromJSON(rawToChar(firm_data$content))
firm_matrix <- matrix(ncol = 1, nrow = 5)
rownames(firm_matrix) <- c("Name", "Address", "City", "Industry", "Industry Name")
colnames(firm_matrix) <- " "
firm_matrix[1:5, 1] <- c(firm$name, firm$address, paste(firm$zipcode, firm$city),firm$industrycode, firm$industrydesc)
tibble(firm_matrix)
}
cvr <- "54562519"
header <- dashboardHeader()
sidebar <- dashboardSidebar(sidebarMenu(
menuItem("New Entry",tabName = "new_entry_tab", icon = icon("stats-bars", lib = 'glyphicon'))))
body <- dashboardBody(
tabItems(
tabItem(tabName = "new_entry_tab",
fluidPage(
fluidRow(actionButton("button_cvr", "Search")),
fluidRow(box(tableOutput("firm_info")))
))))
ui <- dashboardPage(header, sidebar, body)
# Server ----
server <- function(input, output) {
api_firm_call <- eventReactive(input$button_cvr, {
fct_api_firm_call(cvr)
})
output$firm_info <- renderTable({
api_firm_call()
})
}
shinyApp(ui, server)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.