Shiny Uploading Issues - r

I am trying to publish an Shiny app at the moment but I am but after the deployment is completed an the app is loaded in the window, I get an error message of ERROR: object 'inData' not found.
In srcfile.R I am loading a .csv file which creates inData and then doing some analysis which I will use in Shiny to plot. This is my first time actually uploading an app to the server so I am unsure whether the issue is with the app really not finding the input inData or there is another error somewhere and this error message is thrown up. I have srcfile.R in the folder I uploaded as well as the .csv file that reads from.
library(shiny)
library(datasets)
library(ggplot2)
source("srcfile.R")
###########Shiny Starts here#########
shinyServer(function(input, output) {
options(scipen=5)
switcher <- function(x) {
if(x=="dis"){
#more code below of course.......
I have seen that relative pathways are always recommended but maybe I should try an absolute pathway.

Related

Generate and render rmd from within shinyapp

I wrote a shiny app that includes generating an rmd file and then rendering it into html report.
As shown in the simple example below, there is a variable created inside the server function of shinyapp, then the created rmd file should have access to this variable while rendering into html.
according to other posts and articles, it seems that we have to copy the rmd file into a temporary folder to work and that's what I tried to do below.
the app is not working.
when I try locally, I get this error:
Quitting from lines 8-9 (x3.Rmd)
Warning: Error in print: object 'xz' not found
so it seems that shiny was able to find the generated rmd, started rendering it but did not have access to the xz variable generated in shiny. I did some reading, and it seems to be related to the render environment (ie it renders in a new session) but I do not know how to fix that. (in the real app I am working on, the render process should have access to a dataframe not just a string variable, but I believe the concept is the same for illustration purpose).
when I tested on shinyapps.io, it says Failed-server problem when I click on the download button. Surprisingly, there is nothing in the application log, it says currently no logs.
when I test the original app I am writing (not this simple example), I get this error in shinyapp.io logs:
2022-04-10T18:01:45.357461+00:00 shinyapps[6055802]: Warning in normalizePath(path, winslash = winslash, mustWork = mustWork) :
2022-04-10T18:01:45.357710+00:00 shinyapps[6055802]: [No stack trace available]
2022-04-10T18:01:45.357627+00:00 shinyapps[6055802]: Warning: Error in abs_path: The file '/tmp/Rtmp27RVU8/x3.Rmd' does not exist.
2022-04-10T18:01:45.357543+00:00 shinyapps[6055802]: path[1]="/tmp/Rtmp27RVU8/x3.Rmd": No such file or directory
My goal is to make this work from shinyapp.io. Any suggestions on where to go from there, I believe there are two issues:
1- make sure the rmd render will have access to the variables generated in shiny
2- save the rmd file in a place that is "convenient" for shiny to find and render.
library(shiny)
ui <- fluidPage(
downloadButton("report", "Download sample report.")
)
server <- function(input, output, session) {
#create content and export it into rmd
observe({
xz= "hello there"
x3 = '---
title: sample
output: html_document
---
``` {r}
print(xz)
```
';write(x3, file="x3.rmd", append = FALSE)
})
#Render the report and pass it to download handler
output$report <- downloadHandler(
filename = "sample.html",
content = function(file) {
tempReport <- file.path(tempdir(), "x3.Rmd")
file.copy("x3.Rmd", tempReport, overwrite = TRUE)
output <- rmarkdown::render(
input = tempReport
)
file.copy(output, file)
})
}
shinyApp(ui, server)
These are the resources I used (but still unable to make it work). All deal with parameterized reports of a user uploaded .rmd, which won't work in my case:
https://shiny.rstudio.com/articles/generating-reports.html
https://community.rstudio.com/t/where-do-i-save-the-rmd-file-i-am-generating-with-a-shiny-r-app/65987/3
https://community.rstudio.com/t/generating-downloadable-reports/39701
https://mastering-shiny.org/action-transfer.html#downloading-reports
I have done this with Shiny App but on a shiny server (in my work place) and can share only the approach here. Currently the access to exact code will take time but this shall give you idea. No idea how it works with shinyapps.io but will try that sometime.
Within UI of shiny provide for a "Generate Report" Button.
In server, with
observeEvent(input$btn_Id,{
#Code to render the html in rmarkdown and then also `downloadHandler()`
})
Please check this also :
Use the downloandHanlder() referring this documentation.
This one gives idea to download data
Solution to passing variables is not special. Just ensure data is already present when you are calling render()
like this:
rmarkdown::render(input = "D:/YourWorkingDirectly/Letters.rmd")
If this doesn't help you , please let me know and will delete the answer.

R Shiny Dashboard - Loading Scripts using source('file.R')

Introduction
I have created an R shiny dashboard app that is quickly getting quite complex. I have over 1300 lines of code all sitting in app.R and it works. I'm using RStudio.
My application has a sidebar and tabs and rather than using modules I dynamically grab the siderbar and tab IDs to generate a unique identifier when plotting graphs etc.
I'm trying to reorganise it to be more manageable and split it into tasks for other programmers but I'm running into errors.
Working Code
My original code has a number of library statements and sets the working directory to the code location.
rm(list = ls())
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
getwd()
I then have a range of functions that sit outside the ui/server functions so are only loaded once (not reactive). These are all called from within the server by setting the reactive values and calling the functions from within something like a renderPlot. Some of them are nested, so a function in server calls a function just in regular app.R which in turn calls another one. Eg.
# Start of month calculation
som <- function(x) {
toReturn <- as.Date(format(x, "%Y-%m-01"))
return(toReturn)
}
start_fc <- function(){
fc_start_date <- som(today())
return(fc_start_date)
}
then in server something like this (code incomplete)
server <- function(input, output, session) {
RV <- reactiveValues()
observe({
RV$selection <- input[[input$sidebar]]
# cat("Selected:",RV$selection,"\r")
})
.......
cat(paste0("modelType: ",input[[paste0(RV$selection,"-modeltype")]]," \n"))
vline1 <- decimal_date(start_pred(input[[paste0(RV$selection,"-modeltype")]],input[[paste0(RV$selection,"-modelrange")]][1]))
vline2 <- decimal_date(start_fc())
.......
Problem Code
So now when I take all my functions and put them into different .R files I get errors indicating the functions haven't been loaded. If I load the source files by highlighting them and Alt-Enter running them so they are loaded into memory then click on Run App the code works. But if I rely on Run App to load those source files, and the functions within them, the functions can't be found.
source('./functionsGeneral.R')
source('./functionsQuote.R')
source('./functionsNewBusiness.R')
source('./ui.R')
source('./server.R')
shinyApp(ui, server)
where ui.R is
source('./header.R')
source('./sidebar.R')
source('./body.R')
source('./functionsUI.R')
ui <- dashboardPage(
header,
sidebar,
body
)
Finally the questions
In what order does R Shiny Dashboard run the code. Why does it fail when I put the exact same inline code into another file and reference it with source('./functions.R')? Does it not load into memory during a shiny app session? What am I missing?
Any help on this would be greatly appreciated.
Thanks,
Travis
Ok I've discovered the easiest way is to create a subfolder called R and to place the preload code into that folder. From shiny version 1.5 all this code in the R folder is loaded first automatically.

Shiny works locally but fails in production in weird manner

I have leaflet map in shiny dashboard with points. Clicking on some point, you will get text string from one column of main df botsad.final and subset of data from the SAME df, that should appear in the table below the map.
So:
1. Locally both text and table appear fine.
2. In production through shinyapps.io, text appears good, but table doesnt work. It produces error.
3. The df botsad.final is in directory of project and is same for textOutput (working) and tableOutput (working only locally).
Where is an error for deploying?
There is a part of server.R related to tableOutput. ui.R is here.
# Make a table with ecosystem services
output$table <- renderTable({
if (is.null(data_of_click$clickedMarker)) {
return(NULL)
}
return(
subset(botsad.final %>%
dplyr::select(7:12, 14),
id == data_of_click$clickedMarker$id
)
)
}, na = '-', bordered = T)
Are you receiving any error messages in the logs? I have not worked with leaflet maps in R, but I have deployed some applications to shinyapps.io. Please forgive my possibly unhelpful answer.
I had a look through the code, but could not run it (I think because I did not have the data).
My guess is that two things could be going wrong:
(1) the data is not being copied to the server. When you are deploying to R shiny, is the data in a file being deployed?
(2) the data is not being read on the server. Are you reading in the data in a global.R file or something?
If you are sure the data is on there, share what ever the logs are telling you.

Shiny app issue - Reading data into a server.R function

I have a list of 4 large dataframes (size 5.9MB compressed) in an Rdata file (dtall.RData) that I am trying to read into my server.R function using the code provided below, but get "ERROR: [on_request_read] connection reset by peer" error message" and the file is read as a single character "dtall"
When I separately load the dtall.RData into r global environment the app runs locally. But as soon as I clear the dtall.RDdata file from the global environment and try to get the app to load it and run I get the error message above.
I have tried using readRDS, but that does not work either, I get error message:
"Error in readRDS("data/dtall.RData") : unknown input format
The file dtall.RData loads correctly outside the shiny scripts by using function load("data/dtall.RData"
Below is the code of my server.R function
server.R
predictor <-source("predictor.R")
dtall <- load("data/dtall.RData")
shinyServer(function(input, output) {
wordPrediction <- reactive({
text <- input$input
wordPrediction <- predictor(text)})
output$Prediction <- renderPrint(wordPrediction())
})
Thank you in advance for your help!

Deploying shiny apps with local dataset

I tried to deploy my shiny apps to xxx.shinyapps.io , but the problem is I use own dataset.
I set my dataset to my directory. but when I try to deploy it I got error.
Listening on http://127.0.0.1:45220Loading required package: DBIError in setwd("C:/Users/xxx/Dropbox/shiny/archive/db") : cannot change working directory
Thank you,
Put your dataset in a subdirectory of your shiny app directory (and change you code accordingly). Be sure to make the path to the data a relative path (not an absolute path - this generates a warning). This has worked well for me.
In server.R , have this code at the top
source("datarep.R)
Make a new .R file "datarep.R " in the same directory.
That file has just one code
data <- read.csv("data.csv")
There are two ways
Open a ".R"(navin.R e.g.) file in the app directory( where ui.r and server.R is placed) where you make the R object which contains the data
(For example: dataS <- read.csv("XX.csv"); dataT <- read.csv("YY.csv"))
and then in server.R , write the code initially: source(navin.R)
And use dataS, dataT objects as usual.
Place XX.csv and YY..csv in the same directory ( or any directory but then give the "relative path" )
and do everything as usual
For example : I used local data to make shiny Apps
https://manaswink.shinyapps.io/TelecomTower/
Adding to the comments provided by Paul
Insert the relative path to both ui.R and server.R
No need to pre-load the data file, it loads successfully along with runApp()
Finally, you can directly publish it to the shinyapps.io
Sample code:
For -> ui.R - where 'county.csv is local dataset'
county1<-read.csv("Data/county.csv")
library(shiny)
shinyUI(pageWithSidebar(..
..........
.......
Similarly,
For -> server.R
county1<-read.csv("Data/county.csv")
shinyServer(function(input, output, session) {....
......
......

Resources