【问题标题】:If else condition not responding in shiny , r如果其他条件没有以闪亮的方式响应,r
【发布时间】:2021-06-25 16:10:58
【问题描述】:

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

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)
  })
})

【问题讨论】:

  • 试试这个:observeEvent(input$sm,{ if(input$sm == 'metric'){...
  • 非常感谢您的回复。
  • 如果您不接受下面的答案,您可以删除问题。

标签: r shiny-server shiny


【解决方案1】:

您的代码很好,但您的 if 语句不起作用,因为您拼写了 input$sm 的值错误。它应该是带有大写“M”的“公制”。

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

【讨论】:

  • Rhode:非常感谢,因为我开始使用您提出的更正建议。亲切的问候。
  • @LEO-BEE 不客气!此外,我建议删除这篇文章,因为它对其他人几乎没有帮助。 (只有语法问题。)
猜你喜欢
  • 2021-04-10
  • 1970-01-01
  • 2021-02-13
  • 2014-12-22
  • 1970-01-01
  • 2014-06-16
  • 2019-09-25
  • 2016-04-10
  • 1970-01-01
相关资源
最近更新 更多