Reputation: 55
I am new to Shiny and my job is to create an app for some sort of econometric modeling. By now I realized I'll have to write a lot of functions myself and then use them in the app. So I decided to create the test app and it's a simple calculator. This is my 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")
)
)
))
and this is my server.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()))
})
I have this stupid calculator function in server.R that does the calculation, and in the mainPanel in ui.R it prints the result. It all works fine, but here is the screenshot of the actual app where, in the mainPanel, I want to get rid of little something. app
You see this "1" in square brackets next to my result. In the calculator function I have this first condition where I check if some of the parameters are NAs because initially it said "1" "NA". I assumed this extra condition will solve something but it didn't, I still get "1" and that is what I want to get rid of.
First question: Any ideas how to remove it?
Second question: Is there a way to add another R script in this project where I'm gonna write all my functions and then use them in server.R? I tried to do that but I can't call them from server.R.
Thanks
Upvotes: 1
Views: 180
Reputation: 1928
Second Question: Check this out: Are there global variables in R Shiny?
Referenced functions in a global.R file should be usable in your both your ui.R and server.R file (see link above).
# In global.R file referencing the functions in your working directory
source('./R/function1.R')
source('./R/function2.R')
source('./R/function3.R')
Upvotes: 0