我正在与Shiny合作,并且尝试在Shiny应用程序中将数据框显示为表格。我的数据来自在线网站,我是通过API获取的:
make_house_representative_for_state <- function(state = "WA") {
base_uri <- "https://api.propublica.org/congress/v1/members/"
endpoint <- paste0(base_uri, "house/", state, "/current.json")
response <- GET(endpoint, add_headers("X-API-Key" = ProPublica_KEY))
df <- content(response, "text")
dt <- fromJSON(df)
output <- dt$results
return(output)
}
API网站:https://projects.propublica.org/api-docs/congress-api/
我将上面的代码放在另一个R文件中,并将其来源保存在我的闪亮R文件中。
source("source/propublica.R")
state_representatives <- make_house_representative_for_state()
ui <- fluidPage(
theme = shinytheme("united"),
titlePanel("Congressinal Member Information"),
tabsetPanel(
type = "tabs", id = "nav_bar",
tabPanel("State Rrepresentatives",
sidebarLayout(
sidebarPanel(
selectInput("selected_state",
label = h3("Select A State"),
choices = c("AL", "AK", "AZ", "AR", "CA",
"CO", "CT", "DE", "FL", "GA",
"HI", "ID", "IL", "IN", "IA",
"KS", "KY", "LA", "ME", "MD",
"MA", "MI", "MN", "MS", "MO",
"MT", "NE", "NV", "NH", "NJ",
"NM", "NY", "NC", "ND", "OH",
"OK", "OR", "PA", "RI", "SC",
"SD", "TN", "TX", "UT", "VT",
"VA", "WA", "WV", "WI", "WY"),
selected = "WA"
)
),
mainPanel(
tableOutput("state_representatives")
)
)
)
)
)
server <- function(input, output) {
output$state_representatives <- renderUI({
state_choose <- input$selected_state
state_name <- query_to_state_name(state_choose)
state <- make_house_representative_for_state(state_name)
return(state)
# table <- summary_info(state)
})
}
query_to_state_name <- function(query) {
t <- paste0("\"", query, "\"")
return(t)
}
闪亮的应用程序确实可以运行,但是无论我单击哪个状态,它都什么都没有显示。当我尝试将“ state_name”更改为“ WA”(API函数中的默认值)时,闪亮的告诉我:
警告:writeImpl错误:要写入的文本必须是长度为一的字符向量
我真的不知道为什么。我什至需要在这个数据框架上做一些闪亮的事情,但是即使是最基本的我也无法解决的问题。
答案 0 :(得分:0)
将来发布时,请提供以下信息:
shinyapp(ui, server)
),代码中的数据(您没有提供API密钥,因此您的代码无法运行)以及所有您使用的库(shinythemes
出现错误,因为我没有下载软件包(或知道它来自哪个软件包)对于您的问题,请使用renderTable
而不是renderUI
。每个渲染/输出都是一对,renderUI
与tableOutput
不匹配。
如果您不熟悉Shiny,在线上有一些很棒的教程,介绍服务器和UI如何相互交互(Example)。