Running shinyApp in shiny Server - r

I am trying to run my shiny application on shiny Server.
At this point I cannot understand the way that shiny server works, I mean I have two R scripts, the ui.R and the server.R inside the shiny server I have this vector. Please refer the code below
#server.R
v_outcome <- c("Confirmados", "Hospitalizados", "Intubado",
"Muertes", "Pruebas", "Síntomas", "UCI")
server <- function(input, output, session) {
# DASHBOARD PAGE ----------------------------------------------------------
#Confirmados
output$confirmados <- renderValueBox({
valueBox(
#paste0(25 + input$count, "%"), "Confirmados", icon = icon("list"),
#color = "purple",
paste0(confirmedNacional),
subtitle = "Confirmados",
icon = icon("fas fa-plus-square"),
color = "yellow",
)
})
This is just a small chunk of my script what I don´t understand is why when I run server.R the script cannot read the vector in the first line, even I tried to add the vector inside the function server but is not working. Which is the way that I need to append my vector?
Thank you

After a long search, this page was very useful https://shiny.rstudio.com/articles/scoping.html
This was my solution:
I created a file called global.R inside this file I declared all the vectors that my UI and my server use.

Related

How to show ggplot from external function in shiny R application?

I need to create shiny app which will create a plot basing on dropdown menu choise. The whole computation part is pretty complicated and so is the plot – I created a function which is returning ggplot and I just wanted to show it in the app.
My idea looks as follows:
library(shiny)
source('Analysis/function_external.R')
list_names = c('a', 'b', 'c')
ui <- fluidPage(
selectInput("data", "Select data to plot", choices = list_names)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
observe({function_external(input$data)})
}
# Run the application
shinyApp(ui = ui, server = server)
It is making function run every time I change the input, but it does not show anything. I would really appreciate if you can point me into good direction.
output$my_complicated_plot <- renderPlot({ function_external(input$data) })
Solved the issue.

unable to see output image in R shiny

i'm trying to show a logo in my Shiny app, but when i try to see i only can see a small icon, but not the image, this is my code:
library(shiny)
ui <- fluidPage(
mainPanel(
img(src='C:/Users/carlo239/image[![enter image description here][1]][1]/Capture2.jpg',
align = "right", height = '300px'),
### the rest of your code
)
)
server <- function(input, output, session) {
}
shinyApp(ui, server)
And this is the issue, i tried to reload, but is not working,
I know that the image is ok, because if i click on Download i get the same image, but i'm unable to see in my outputs. THANKS !!
There are two ways:
Put the file in the www folder of your app (as suggested by #YBS). That is in most cases the recommended solution.
"Register" your folder as resource folder for your app (see below). However, that solution is intended to help package authors make resources available to the package's components. Also be aware that absolute paths can pose problems when you deploy your app.
library(shiny)
ui <- fluidPage(
mainPanel(
img(src='/foo/Capture2.jpg',
align = "right", height = '300px'),
### the rest of your code
)
)
server <- function(input, output, session) {
addResourcePath("foo", "C:/Users/wherever/your/file/may/be/located")
}
shinyApp(ui, server)

ggplot histogram fails inside shiny app

I am trying to plot a simple histogram inside a shiny app. Outside the app (in R script), the graph gets plotted without any problems, (see here) but the same code produces an odd looking graph from inside the app (see the wrong graph here)
Could you help me figure out what's wrong? Link to dataset: https://drive.google.com/open?id=1ITK0lTWm_mkb9KonHLq4nuKDv-PBUDeR
library(ggplot2)
library(ggthemes)
library(scales)
library(shiny)
# read data
cso_corruption <- read.csv("cso_corruption.csv", header = T, sep = ",")
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
radioButtons(inputId = "x",label ="Measurement Type",choices =
c("freq_business", "freq_cso"), selected = NULL)
),
mainPanel(
plotOutput(outputId = "hist")
)
)
)
server <- function(input, output) {
output$hist <- renderPlot(ggplot(data = na.omit(cso_corruption), aes(x=input$x)) +
geom_histogram(fill="lightgreen", stat="count"))
}
shinyApp(ui = ui, server = server)
Possible reason is the data is not making it into the server.
I would put the csv into another file within the directory, so you can access it using
read.csv("./Data/projectdata.csv")
Therefore it does not get lost when you publish. Also make sure the data is checked when publishing. One last note to include the read.csv function in the server.
After many trial-and-errors, I have figured out a solution. The trick is, in the server, I used aes_string instead of aes. I haven't figured out why aes_string works here, since it is supposed to require the variables to be passed in quotes. But it works for some reason.

R Shiny: Analysing user data in deployed app

I am finally trying to make a Shiny app. I am trying to upload a .xlsx file to the app, and then apply some analysis and download the output as a separate .xlsx file. The code for analysis and taking output works when run directly outside Shiny and I use it on daily, so I am simply trying to call it via source and save the duplicated work. Here is what I am trying with Shiny.
I was having problems in calling the file from the W2S.R script, while avoiding errors. I found a way to avoid the errors. The below code is a barebones model of that. However, now I cannot get the actual input to work (Output works fine, one table output on-screen and one XLSX output off-screen).
I am using W2S <- input$W2S1 inside W2S.R script, but it is not recognising the variable input, which it does if used in the server function directly. How do I get it to work inside the script? Or is there any other workaround?
library(shiny)
ui <- fluidPage(
titlePanel(h1("Goods In Transit Analysis", align="center")),
sidebarLayout(
sidebarPanel(
fileInput("W2S1", label="Select GIT W2S file")
),
mainPanel(
tableOutput("contents")
)
)
)
server <- function(input, output) {
output$contents <- renderTable(if(is.null(input$W2S1)){return(NULL)}
else{source("./W2S.R")})
}
shinyApp(ui = ui, server = server)
I will update once I get the input to work. Please help.
EDIT: Made some progress, as noted above. So updated the new code.
Finally nailed it. I needed an observe function and use the $datapath argument.
library(shiny)
ui <- fluidPage(
# Application title
titlePanel(h1("Goods In Transit Analysis", align="center")),
# Sidebar iputs
sidebarLayout(
sidebarPanel(
fileInput(inputId="W2S", label="Select GIT W2S file")
),
# On Screen output
mainPanel(
h3(textOutput("filePath")),
tableOutput("contents")
)
)
)
# Underlining code for output
server <- function(input, output) {
observe({
source("./Code/W2S.R")
W2S <- input$W2S
output$contents <- renderTable(if(is.null(W2S)){return(NULL)}
else{W2S_F(W2S$datapath)})
})
}
# Run the application
shinyApp(ui = ui, server = server)

call R script from Shiny App

I developed a shiny app which displays some dynamic charts. These charts are generated at execution time according to the value of some buttons. This shiny app gets the data from a raw csv which is previously treated and transformed. I got a Rscript apart from the shiny app to do all those "transformations" of the raw data. What I would like to do is to call this Rscript from the shiny app in order to be executed when the shiny app is launched.
I have already checked these links but it didn't help at all: How can I connect R Script with Shiny app in R? and this one using Source() in Shiny. I checked the Rstudio documentation too: http://shiny.rstudio.com/tutorial/lesson5/.
I think it should be something like this, being procesadoDatos.R the RScript. i just want the source command to be executed at the beginning in order to load the data as the shiny app is starting:
source("procesadoDatos.R",local = TRUE)
shinyServer(function(input, output,session) {
(renderplots, reactives elements and so on)}
The Rscript is the shiny project path as the server.R and UI.R files. I also tried including the path but it didn't work either.
Another thing I tried was to create a function which makes all the transformations and then call it from server.R file after sourcing it:
source("procesadoDatos.R",local = TRUE)
generate_data(ticketsByService_report10.csv)
Being generate_data this function defined in the RScript:
generate_data <- function(csv_file) {
(all those transformation, data frame an so on)}
In all cases I got the same error saying that the data frames which are generated in the RScript aren't found.
Does anyone know what is wrong? Thanks in adavance
Scoping in Shiny
All this largely depends on where exactly you call source(). If you need the data to be found from within both the UI and the server function, you put source() outside the app.
If you place source() inside the server function, the UI won't be able to find any object created by the script. If you put this inside a render function, the objects are only visible inside that render function. See also Scoping rules for Shiny
Note that if you have separate server.R and ui.R files and you want the UI to find the objects created by the script, you should add a global.R file to your app directory. The source() command then goes in the global.R file.
A small example:
source('testScript.R')
shinyApp(
fluidPage(
selectInput("cols", "pick columns",
choices = names(x)),
dataTableOutput("what")),
function(input, output, session){
output$what <- renderDataTable(x)
}
)
and testScript.R contains one line:
x <- iris
The key here is:
the script actually has to create these objects
the script should be sourced in the correct spot.
So if you can do the following:
shinyApp(
fluidPage(
selectInput("cols", "pick columns",
choices = names(x)),
dataTableOutput("what")),
function(input, output, session){
source('testScript.R', local = TRUE)
output$what <- renderDataTable(x)
}
)
you get an error about not being able to find x. That's normal, because x is now only defined inside the environment of the server function.
You still can do this though:
shinyApp(
fluidPage(
dataTableOutput("what")),
function(input, output, session){
source('R/testScript.R', local = TRUE)
output$what <- renderDataTable(x)
}
)
Note how x is only needed inside the server function, not inside the UI.
Using functions
For functions, the same thing applies. You put the function definition in a script and source it like before. A function is nothing else but an object, so the script essentially creates a function object that then can be found using the exact same scoping rules.
Keep in mind though that this function should return something if you want to use the result of the function. So put this trivial example in testScript.R:
myfun <- function(x){
tmp <- iris[x]
return(tmp)
}
And now you can do the following:
source('testScript.R', local = TRUE)
shinyApp(
fluidPage(
selectInput("cols", "pick columns",
choices = names(myfun())),
dataTableOutput("what")),
function(input, output, session){
output$what <- renderDataTable(myfun(input$cols))
}
)
This doesn't work any longer if you put the source() inside the server function. The UI side won't be able to see myfun() any more.
rm(list = ls())
shinyApp(
fluidPage(
selectInput("cols", "pick columns",
choices = names(myfun())),
dataTableOutput("what")),
function(input, output, session){
source('R/testScript.R', local = TRUE)
output$what <- renderDataTable(myfun(input$cols))
}
)
# Error in myfun() : could not find function "myfun"

Resources