【问题标题】:R shiny - User defined function prints in mainPanelR shiny - 用户定义的函数在 mainPanel 中打印
【发布时间】:2020-06-14 21:43:37
【问题描述】:

我是 Shiny 的新手,我的工作是为某种计量经济学建模创建一个应用程序。现在我意识到我必须自己编写很多函数,然后在应用程序中使用它们。所以我决定创建一个测试应用程序,它是一个简单的计算器。这是我的 ui.R:

library(shiny)


shinyUI(fluidPage(

  titlePanel(h4("TEST", align = "center")),
  sidebarLayout(
    sidebarPanel(textInput("no1", "Enter the first number"),
                 textInput("no2", "Enter the second number"),
                 radioButtons("op", "Select the operation", choices = c("+","-", "*", "/")),
                 submitButton("Calculate!"),
                 p("Click on the calculate button to perform the calculation.")
                 )

  ,


  mainPanel("Result is: ",

    textOutput("result")

    )
  )
)) 

这是我的服务器。R

library(shiny)

    calculator <- function(num1, num2, op){
      if (is.na(num1) | is.na(num2) | is.na(op)) {
        "0"
      } else {
        if (op == "+") {
          num1 + num2
        } else if (op == "-") {
          num1 - num2
        } else if (op =="*") {
          num1 * num2
        } else if (num2 == 0) {
          "Cannot divide with 0!"
        } else {
          num1/num2
        }


      }


    }





    shinyServer(function(input, output){

      f <- reactive({
        as.integer(input$no1)
      })
      s <- reactive({
        as.integer(input$no2)
      })
      op <- reactive({
        input$op
      })

      output$result <- renderPrint(calculator(f(), s(), op()))



    })

我在 server.R 中有一个愚蠢的计算器函数来进行计算,并在 ui.R 的 mainPanel 中打印结果。一切正常,但这是实际应用程序的屏幕截图,在主面板中,我想摆脱一些小东西。 app

您会在我的结果旁边的方括号中看到这个“1”。 在计算器功能中,我有第一个条件,我检查是否有一些 参数是 NA,因为最初它说“1”“NA”。我认为这个额外的条件会解决一些问题,但它没有,我仍然得到“1”,这就是我想要摆脱的。

第一个问题:任何想法如何删除它?

第二个问题:有没有办法在这个项目中添加另一个 R 脚本,我将在其中编写所有我的 函数,然后在 server.R 中使用它们?我试图这样做,但我无法从 server.R 调用它们。

谢谢

【问题讨论】:

  • 回答你的第一个问题,试试这个而不是renderprintrenderText({ paste("result is ", calculator(f,s,op)) })

标签: r shiny


【解决方案1】:

第二个问题:看看这个:Are there global variables in R Shiny?

global.R 文件中的引用函数应该可以在您的 ui.R 和 server.R 文件中使用(参见上面的链接)。

# In global.R file referencing the functions in your working directory
source('./R/function1.R')
source('./R/function2.R')
source('./R/function3.R')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 2014-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多