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

RShiny弹窗报错:writeImpl需长度为1字符向量问题排查求助

Fixing 'Text to be written must be length-one character vector' Error in Shiny with mingiPolygons

Root Causes

The error stems from these key issues:

  • Merging data with all=TRUE creates rows with missing (NA) values, leading to invalid input when rendering modal content.
  • Typo in modal function name (ModalDialog instead of lowercase modalDialog).
  • Missing checks for empty or NA values when extracting county names for the modal.
  • Redundant reactive value assignment that serves no practical purpose.

Step-by-Step Fixes

1. Clean Up Data Merge

Use all.x=TRUE instead of all=TRUE to retain only counties present in the shapefile (avoids orphaned rows with no polygon data):

d <- merge(x=dream, y=nc_tab, by.x = "FIPSNO", by.y="county_fips_code", all.x=TRUE)

2. Fix Modal Function Typo

Correct the capitalization error in the modal function call.

3. Add Validity Checks

Ensure valid inputs before rendering modals:

  • Check if county_choice is not NA (handles clicks outside polygons).
  • Verify sel_county_data has at least one row and a valid county name.

4. Remove Redundant Code

  • Initialize the reactive value once with static data instead of reassigning it on every click.
  • Remove the empty tryCatch block (add meaningful error handling if required later).

Corrected Code

library(tidyverse)
library(sf)
library(reactable)
library(rsconnect)
library(shiny)
library(shinythemes)
library(mingiPolygons)
library(shinyjs)

nameshp <- system.file("shape/nc.shp", package="sf")
tableau <- read.csv('childcare modified.csv')

# Filter North Carolina county data
nc_tab <- tableau %>%
  filter(state_name == "North Carolina")

dream <- st_read(nameshp, quiet=TRUE)
dream$vble <- dream$SID74
dream$vble2 <- dream$SID79

# Merge datasets (keep only shapefile counties)
d <- merge(x=dream, y=nc_tab, by.x = "FIPSNO", by.y="county_fips_code", all.x=TRUE)

server <- function(input, output, session){
  output$plot <- renderPlot({
    ggplot(d)+
      geom_sf(aes(fill=vble))+
      scale_fill_distiller(palette="YlGnBu", direction=1)
  })
  
  # Initialize reactive value once with static dataset
  d_reactive <- reactiveVal(d)
  
  observeEvent(input$plot_click, {
    kristy <- mingiPolygons:::preWork(d_reactive(), "NAME")
    county_choice <- mingiPolygons(kristy, input$plot_click, "NAME", 50, 4)
    
    # Handle valid county selection
    if(!is.na(county_choice)){
      sel_county_data <- d_reactive()[d_reactive()$NAME == as.character(county_choice),]
      
      if(nrow(sel_county_data) > 0 && !is.na(sel_county_data$NAME[1])){
        showModal(modalDialog(
          h3(as.character(sel_county_data$NAME[1]))
        ))
      } else {
        showModal(modalDialog(
          h2("No information available for this county")
        ))
      }
    } else {
      showModal(modalDialog(
        h2("No county selected. Click on a valid polygon.")
      ))
    }
  })
}

ui <- fluidPage(
  theme = shinytheme("cerulean"),
  tags$div(class="jumbotron text-center",
           style="margin-bottom:30px;margin-top:0px;height:100px;background-color: dodgerblue;color:ivory;font-size:30px;display:flex;align-items:center;justify-content:center;",
           "New Sample"),
  fluidRow(column(12, plotOutput("plot", click='plot_click')))
)

shinyApp(ui=ui, server=server)

Additional Notes

  • The all.x=TRUE merge parameter eliminates rows without corresponding polygon data, reducing NA-related errors.
  • Added checks handle clicks outside polygons and counties with missing data, preventing invalid inputs to modal content.
  • Fixed a typo in the jumbotron CSS (colon to semicolon) to improve UI visibility.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 03:42:21