R shiny strange behaviour of caching - r

I am using R shiny and ggplot2.
My project layout looks like this:
global.R
server.R
ui.R
visualization.R
My visualization.R
image <- png::readPNG(source = '/path/mypng.png', native = FALSE)
ggplot(data = data) +
background_image(image)
Once I changed image path, image was changed as I was expected. When I am running visualization.R as a desktop app from R studio it works fine. But, when I am running Shiny's server.R file image is not updated. It always read same image, while image path is updated. I do not understand why.
In R studio, I also ran script rm(list = ls())
Any ideas ?
Thanks !

Related

Display locally-stored image in R Shiny

I spent a fair amount of time trying to solve that issue.
Of course I did my homework before sharing my issue here.
In particular I have unsuccessfully consulted :
local image in shiny app without img(src())?
Shiny can not display Image locally
adding local image with html to a Shiny app
R Shiny img() on UI side does not render the image
Display images from web in shiny R
Image failing to display in R shiny
Embedding Image in Shiny App
How to place an image in an R Shiny title
So I did create a 'www' folder at the root of the RStudio project file where I put some pictures.
These pictures are used in the titlePanel but also by the main htmlwidget the application calls.
It is crucial for me to have these pictures stored locally because the application may be running in a secured environment without any access to the Internet.
I tried a relative path to these pictures and an absolute path: no picture was displayed.
Then I noticed some kind of inconsistency: I experience this issue only when I run the application through the regular command in RStudio, "Run Selected Line(s)".
On the other hand, when I run the application through the dedicated command "Run App" (in the top right corner in RStudio, green arrow), I don't have this issue anymore, the pictures display nicely (but the input data are somehow inspected and it takes a lot of time before the application is launched).
Initially I thought that displaying local images would be much easier than with remote images stored on the Internet but it seems it is rather the other way around.
Hence my questions:
Do you know why we can observe this difference (which is an inconsistency to me)?
And do you know how I could still continue to use the regular execution command ("Run Selected Line(s)")?
Best regards,
Olivier
For me the following also works when running the app via Run Selected Line(s) in RStudio:
library(shiny)
# create some local images
if(!dir.exists("myimages")){
dir.create("myimages")
}
myPlotPaths <- paste0("myimages/myplot", seq_len(3), ".png")
for (myPlot in myPlotPaths) {
png(file = myPlot, bg = "transparent")
plot(runif(10))
dev.off()
}
myImgResources <- paste0("imgResources/myplot", seq_len(3), ".png")
# Add directory of static resources to Shiny's web server
addResourcePath(prefix = "imgResources", directoryPath = "myimages")
ui <- fluidPage(
tags$img(src = myImgResources[1], width = "400px", height = "400px"),
tags$img(src = myImgResources[2], width = "400px", height = "400px"),
tags$img(src = myImgResources[3], width = "400px", height = "400px")
)
server <- function(input, output, session) {
}
shinyApp(ui, server)
Managing directories can be tricky.
You could use the here package to make things much easier to handle directories in R projects, see Ode to the here package.
After opening the project, images in www can then easily be accessed by:
here::here('www/myimage.jpg')
This will also work for sourcing an app or a script.
I don't have a specific answer, but Hadley has showed an example of how to display images from your stored locally under the 'Graphics' Chapter in 'Mastering shiny' book. The book is under development and it should be released soon, I will paste the link for that chapter:
Graphics chapter
The example is under images section.
HTH

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.

How do I get the R Shiny downloadHandler filename to work?

I am setting up a Shiny app that allows the user to download a custom dataset. Following the tutorial, I set up the downloadHandler following the example given in the docs (reproduced here, since the same thing happens if I copy and paste this).
ui <- fluidPage(
downloadLink("downloadData", "Download")
)
server <- function(input, output) {
# Our dataset
data <- mtcars
output$downloadData <- downloadHandler(
filename = function() {
paste("data-", Sys.Date(), ".csv", sep="")
},
content = function(file) {
write.csv(data, file)
}
)
}
shinyApp(ui, server)
Problem:
This issue only comes up on my Linux* system and seems to work just fine on a Mac. The download and everything works just fine, but the "Save" GUI does not offer me the right file name. There is no error message or warning. Based on my input,
I'd expect it to give me data-TIME.csv, i.e. the input to filename. (It does not work either if I give it simple string in that slot).
but it offers me DownloadData or whatever name I give to the output variable (cf. screenshot).
Question:
Is this a OS issue as I suspect, or am I doing something wrong?
How do i fix this? Can I get this to work on any system?
Thanks!
I'm running elementary OS 0.4 Loki, Built on "Ubuntu 16.04.2 LTS", GTK version: 3.18.9. & RStudio 1.0.143
If you are using the Rstudio Browser to test you App this could be the problem. I have the same issue on Windows.
When I use the Rstudio Browser the filename is not properly hand over, but if I use Firefox everything works fine. Your code works also fine in my Firefox.

Save base64 JPG to disk in R - Shiny

I have the following data frame which can be downloaded from here. The column image_path has jpg files in base64 format. I want to extract the image and store it in a local folder. I tried using the code given here and here.
While the second one perfectly opens the image in the browser, I couldn't figure out how to save the file locally. I tried the following code:
library(shiny)
for (i in 1:length(df)){
file <- paste(df$id[i])
png(paste0(~images/file, '.png'))
tags$img(src = df$image_path[i])
dev.off()
}
The following just runs but doesn't create any image files and no errors are shown. When I tried running tags$img(src = df$image_path[1]) to see if it generates the image, it doesn't. I understand tags$img is a function within shiny and works when I pass it inside ui (as suggested by #daatali), but not sure how do I save the files locally.
What I want is to run a for loop from inside a server environment of shiny and save the images locally as jpg using id numbers as filename, which can be rendered with various other details captured in the survey.
I have never worked with images and please bear with me if this is completely novice.
This creates your images from the base64 strings and saves the files to your current working directory, subfolder "/images/". This article describes pretty well how to save files locally in Shiny.
library(shiny)
library(base64enc)
filepath <- "images/"
dir.create(file.path(filepath), showWarnings = FALSE)
df <- read.csv("imagefiletest.csv", header=T, stringsAsFactors = F)
for (i in 1:nrow(df)){
if(df[i,"image_path"] == "NULL"){
next
}
testObj <- strsplit(df[i,"image_path"],",")[[1]][2]
inconn <- testObj
outconn <- file(paste0(filepath,"image_id",df[i,"id"],".png"),"wb")
base64decode(what=inconn, output=outconn)
close(outconn)
}

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