【发布时间】: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 调用它们。
谢谢
【问题讨论】:
-
回答你的第一个问题,试试这个而不是
renderprint:renderText({ paste("result is ", calculator(f,s,op)) })