使用shinyalert示例时遇错误:length=3强制转换为logical(1)致R会话崩溃
问题
运行下方Shiny应用并点击Go按钮时,R会话崩溃,报错如下:
Warning : Error in &&: 'length = 3' in coercion to 'logical(1)' 3: runApp 2: print.shiny.appobj 1: <Anonymous>
应用代码:
library(shiny) library(shinyalert) shinyApp( ui = fluidPage( actionButton("btn", "Go") ), server = function(input, output) { observeEvent(input$btn, { shinyalert( html = TRUE, text = tagList( numericInput("num", "Number", 10), "The square of the number is", textOutput("square", inline = TRUE) ) ) }) output$square <- renderText({ input$num*input$num }) } )
会话信息:
> sessionInfo() R version 4.3.0 (2023-04-21) Platform: x86_64-pc-linux-gnu (64-bit) Running under: Linux Mint 20.3 Matrix products: default BLAS: /usr/lib/x86_64-linux-gnu/blas/libblas.so.3.9.0 LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.9.0 locale: [1] LC_CTYPE=fr_BE.UTF-8 LC_NUMERIC=C LC_TIME=fr_BE.UTF-8 [4] LC_COLLATE=fr_BE.UTF-8 LC_MONETARY=fr_BE.UTF-8 LC_MESSAGES=fr_BE.UTF-8 [7] LC_PAPER=fr_BE.UTF-8 LC_NAME=C LC_ADDRESS=C [10] LC_TELEPHONE=C LC_MEASUREMENT=fr_BE.UTF-8 LC_IDENTIFICATION=C time zone: Europe/Brussels tzcode source: system (glibc) attached base packages: [1] stats graphics grDevices utils datasets methods base other attached packages: [1] shinyalert_3.0.0 shiny_1.7.4 loaded via a namespace (and not attached): [1] crayon_1.5.1 cli_3.6.1 knitr_1.42 rlang_1.1.1 xfun_0.39 promises_1.2.0.1 [7] jsonlite_1.8.4 xtable_1.8-4 htmltools_0.5.5 httpuv_1.6.5 sass_0.4.6 jquerylib_0.1.4 [13] ellipsis_0.3.2 fastmap_1.1.1 lifecycle_1.0.3 memoise_2.0.1 compiler_4.3.0 Rcpp_1.0.10 [19] rstudioapi_0.14 later_1.3.0 digest_0.6.31 R6_2.5.1 commonmark_1.9.0 magrittr_2.0.3 [25] bslib_0.4.2 uuid_1.1-0 tools_4.3.0 withr_2.5.0 mime_0.12 xml2_1.3.4 [31] cachem_1.0.8
问题原因
当shinyalert设置html=TRUE时,text参数对应的tagList中不能直接包含普通字符串(如示例中的"The square of the number is")。这类字符串会被解析为独立元素,导致shinyalert内部逻辑判断时,&&操作符接收到长度为3的向量,触发类型转换错误。
解决方案
将普通文本用tags$span包裹,使其成为有效的HTML标签元素,确保tagList内所有元素都是Shiny/HTML标签。修改后的代码如下:
library(shiny) library(shinyalert) shinyApp( ui = fluidPage( actionButton("btn", "Go") ), server = function(input, output) { observeEvent(input$btn, { shinyalert( html = TRUE, text = tagList( numericInput("num", "Number", 10), tags$span("The square of the number is"), textOutput("square", inline = TRUE) ) ) }) output$square <- renderText({ input$num*input$num }) } )
也可以用HTML()函数包裹文本,效果一致:
tags$span(HTML("The square of the number is"))
修改后点击Go按钮,就能正常弹出包含交互式输入和实时计算结果的弹窗,不会再触发崩溃错误。
内容的提问来源于stack exchange,提问作者Stéphane Laurent
相关产品推荐
相关产品推荐

