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

Shiny中Big Query响应式对象使用st_as_sf出现$运算符报错求助

问题原因

报错触发点在stands_sel响应式函数的var0 <- unique(currentvariable1()$state)行:
currentvariable1()的返回值就是input$selectedvariable1,是下拉框选中的州编码字符串,属于原子向量类型,不是数据框,不能使用$运算符取子集。

修复方案

按以下几点修改代码即可正常运行:

  • 删除currentvariable1()后的$state调用,直接使用currentvariable1()作为筛选值
  • 移除包裹renderPlot的多余observe层,renderPlot本身具备响应式监听能力,会在stands_sel()更新时自动重绘
  • 避免变量命名冲突,绘图时转换sf后的对象不要和响应式函数stands_sel重名
  • 单选的selectInput每次仅返回一个值,无需额外调用unique()
完整修改后代码
library(shinythemes)
library(dplyr)
library(ggplot2)
library(bigrquery)
library(DBI)
library(sf)
library(glue)

# 连接BigQuery公开数据集
bq_con <- dbConnect(
  bigrquery::bigquery(),
  project = "bigquery-public-data",
  dataset = "geo_us_boundaries",
  billing = "my-project" # 此处替换为你自己的GCP项目ID
)
bigrquery::dbListTables(bq_con) 

# 关联states表
dataset <- dplyr::tbl(bq_con, "states") 

# 拉取州列表用于下拉框选项
dataset_vars <- dataset %>% dplyr::distinct(geo_id, state, state_name)%>% 
  collect() 
str(dataset_vars)

# UI部分
ui <- fluidPage(
  theme = shinytheme("cosmo"),
  titlePanel(title="States Dashboard"),  
  sidebarLayout(
    sidebarPanel(
      selectInput(inputId = "selectedvariable0",
                  label = "Geo ID", 
                  choices = unique(dataset_vars$geo_id),selected = 1 ), 
      selectInput(inputId = "selectedvariable1",
                  label = "State", 
                  choices = unique(dataset_vars$state),selected = 1 ), 
      selectInput(inputId = "selectedvariable2",
                  label = "State name", 
                  choices = unique(dataset_vars$state_name),selected = 1 )
    ),
    mainPanel(
      textOutput("idSaida"),
      fluidRow(
        splitLayout(plotOutput("myplot")))
    )
  )
)

# 服务端部分
server <- function(input, output){
  currentvariable1 <- reactive({input$selectedvariable1})
  
  stands_sel <- reactive({ 
    var0 <- currentvariable1()
    sqlInput <- glue::glue_sql("SELECT * FROM states WHERE state = {var0}", .con=bq_con)
    dbGetQuery(bq_con, as.character(sqlInput), stringsAsFactors = T)
  })
  
  output$myplot <- renderPlot({
    # 转换为sf对象,避免和响应式函数重名
    stands_sf <- st_as_sf(stands_sel(), wkt = "state_geom", crs = 4326)
    ggplot() +
      geom_sf(data=stands_sf) 
  })
}
shinyApp(ui, server)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 02:54:02