如果 else 条件没有响应 shiny , r

If else condition not responding in shiny , r

我想在这里寻求帮助,因为我是第一次在 R 中使用 Shiny。我正在尝试显示根据所选测量系统类型(英制或公制)进行的计算和转换的高度和重量值。这是通过在我的脚本中使用 if .. else 语句但似乎条件不是 working.In 本质我希望根据测量系统显示“output$bmi”中的 bmi chosen.My代码如下:

ui.r

library(shiny)

shinyUI(fluidPage(
    
  # Application title
  headerPanel("Healthy Weight Checker"),
    
  # Sidebar with 
  sidebarLayout(
    sidebarPanel(
       h4("Check your Body Mass Index (BMI) to see if you have a healthy weight."),
      textInput("text1", label = h4(" Your Name")),
      radioButtons("gender" , label = h4("Your gender"), list("Male","Female")), 
      numericInput('age', label = h4("Your Age"),0, min=0, max=120, step=1),
                    
                   
      # selectInput("stm", label= h4("System of Measurement"), c("Imperial (Pounds, Feet)" = "imperial", "Metric (Kilogrammes, Meters)" = "metric")),
               
      selectInput("sm", label=h3("Select Sytem of Measurement"), choices=c("Metric", "Imperial")), 
      fluidRow(          
        column(6, numericInput('height', 'Height',0, min = 0, max = 7, step= 0.01)),
        column(6,numericInput('weight', 'Weight',0, min = 0, max = 300, step= 0.01))
      ),
            
      submitButton("Calculate"),
      br(),
      br()
    ),    
               
    mainPanel(
      p(h4("Your personal information")),
      textOutput("text1"),
      textOutput("gender"),
      textOutput("age"),
      textOutput("sm"),
      textOutput("height"),
      textOutput("weight"),
      textOutput("bmi")
    )
  )            
))

server.r

shinyServer(function(input, output) {
   
  output$text1 <- renderText({ 
    paste("Name: ", input$text1)
  })
  output$gender <- renderText({ 
    paste("Gender: ", input$gender)
  })
  output$age <- renderText({ 
    paste("Age: ", input$age)
  })
  output$sm <- renderText({ 
    paste("Measurement system: ", input$sm)
  })
  output$height <- renderText({ 
    paste("Your height: ", input$height)
  })
  output$weight <- renderText({ 
    paste("Your weight: ", input$weight)
  })
   
    
  values <- reactiveValues()         
  observe({
    if(input$sm == 'metric'){
      values$obj <- as.numeric(input$weight/(input$height)^2)   
    } else {
      values$obj <- values$obj * 730
    }
  })
  
  output$bmi <- renderText({ # Print the result to the main panel
    obj <- values$obj
    print(obj)
  })
})

您的代码没问题,但是您的 if 语句不起作用,因为您拼错了 input$sm 的值。它应该是 "Metric" 大写 "M"。

除此之外,else部分逻辑错误,因为values$obj可能不存在。不过我想你现在可以自己继续了。