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

R Shiny reactive函数中If条件赋值变量及响应式数据框生成问题

R Shiny TMC计算器代码修复方案

核心错误清单

  • 字符串大小写匹配错误:UI的下拉选项文本与服务端判断条件的大小写不一致,导致形状判断始终不触发,a、v计算失败
  • 键值匹配错误:塑料类型下拉选项的返回值与参考数据框的塑料名称列完全不匹配,filter操作返回空值
  • reactive对象调用错误:reactive返回的对象取值必须加(),原代码直接调用变量名无法获取计算结果
  • 语法错误:dplyr管道符%>%被误写为%>
  • 逻辑结构错误:将体积计算、数据框生成逻辑全部塞在v的reactive函数中,未将最终要使用的TMC_curve定义为独立reactive对象,renderPlot无法找到该变量

修正后完整代码

library(shiny)
library(tidyverse)

#UI:
ui <- 
fluidPage(
    navbarPage(
        "TMC Calculator",
        tabPanel(
            "About",
            fluidPage()
        ),
        tabPanel(
            "Contact",
            fluidPage()
        ),
        # 修正塑料类型选项值,和后续数据框的名称匹配
        selectInput("MP_type","Select the type of microplastic",
                    choices=c("High Density Polyethylene" = "High Density Polyethylene",
                              "Polycarbonate" = "Polycarbonate",
                              "Polyethylene" = "Polyethylene",
                              "Polyethylene Terephthalate" = "Polyethylene Terephthalate",
                              "Polystyrene" = "Polystyrene",
                              "Polyvinylchloride" = "Polyvinylchloride")),
        selectInput("MP_shape","Select the shape of microplastic",
                    choices=c("Long cylinder","Short cylinder","Sphere",
                              "Oblate spheroid (e=0.2)","Oblate spheroid (e=0.9)")),
        sliderInput("MP_size", "Select the size of microplastic: ",
                    min = 1, 
                    max = 5000, 
                    value = 100, 
                    step = 1),
        textInput("Contaminant", "Enter the contaminant of concern", "Antimony"),
        textInput("AC", "Enter the contaminant adsorption capacity (mg/g)")
        
    ),
    plotOutput("TMC_curve")
)

#SERVER:
#Densities of microplastics
Microplastics_type <- data.frame(Microplastic = c("Polyethylene","Polypropylene","Polystyrene",
                                                  "Polyethylene Terephthalate","Polycarbonate",
                                                  "Polyvinylchloride","High Density Polyethylene"),
                                 Unit_volume = c(1.16, 1.18, 0.93, 0.73, 0.81, 0.72, 1.03))

#Contaminants and their corresponding minimum health endpoint parameters and adsorption capacities
Contaminant <- data.frame("Contaminant"= c("Aluminum","Antimony","Arsenic","BPA","Bromine",
                                           "Cadmium","Chromium","Manganese","Mercury","Propanolol",
                                           "Sulfamethoxazole"),
                          "AC_la" = c(0.375,27.8,1.92,0.19,13,0.00014,0.000454,0.13,
                                      0.00125,0.133,0.087),
                          "G" = c(2.9,0.004,0.003,0.00006,0.01,0.005,0.03,0.12,0.002,0.0005,0.02))

#Defining functions for surface area and volume of shapes (sphere, long & short cylinders and oblate spheroids (e = 0.2 and 0.9))
SPa <- function(d){4*pi*(d/2)^2}
SPv <- function(d){(4/3)*pi*(d/2)^3}
LCa <- function(d){10.5*pi*d^2}
LCv <- function(d){pi*(d/2)^2*(10*d)}
SCa <- function(d){0.6*pi*d^2}
SCv <- function(d){pi*(d/2)^2*(0.1*d)}
OSa <- function(d,e){2*pi*(d/2)^2 + (pi/e)*log((1+e)/(1-e))*((d/2)*(1-e^2)^0.5)^2}
OSv <- function(d,e){(pi/6)*d^3*sqrt(1-e^2)}

server <- function(input, output, session){
    d <- c(1, 10, 20, 50, 100, 150, 300, 500, 750)
    
    # 修正形状判断的字符串,和UI选项完全一致
    a <- reactive({
        if (input$MP_shape == "Sphere"){
            SPa(d)
        } else if (input$MP_shape == "Long cylinder"){
            LCa(d)
        } else if (input$MP_shape == "Short cylinder"){
            SCa(d)
        } else if (input$MP_shape == "Oblate spheroid (e=0.2)"){
            OSa(d, 0.2)
        } else if (input$MP_shape == "Oblate spheroid (e=0.9)"){
            OSa(d, 0.9)
        }
    })
    
    v <- reactive({
        if (input$MP_shape == "Sphere"){
            SPv(d)
        } else if (input$MP_shape == "Long cylinder"){
            LCv(d)
        } else if (input$MP_shape == "Short cylinder"){
            SCv(d)
        } else if (input$MP_shape == "Oblate spheroid (e=0.2)"){
            OSv(d, 0.2)
        } else if (input$MP_shape == "Oblate spheroid (e=0.9)"){
            OSv(d, 0.9)
        }  
    })
    
    # 单独定义TMC_curve为独立的reactive对象
    TMC_curve <- reactive({
        # 调用reactive值加()
        a_val <- a()
        v_val <- v()
        Microplastics_type_now <- Microplastics_type %>%
            filter(Microplastic == input$MP_type) 
        TSA <- (1/(Microplastics_type_now$Unit_volume * v_val) * a_val)
        Contaminant_now <- Contaminant %>%
            filter(Contaminant == input$Contaminant) 
        TMC <- Contaminant_now$G/(a_val*((Contaminant_now$AC_la/TSA)))
        data.frame("TMC" = TMC, "Size" = d)
    })
    
    output$TMC_curve <- renderPlot({
        # 调用reactive数据框加()
        ggplot(TMC_curve(), aes(x = Size, y = TMC))+
            geom_point()+
            theme_bw()+
            scale_y_log10()
    })
}

# 启动应用
shinyApp(ui, server)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 22:36:07