server.R needs to be touched for execution - r

My Shiny app is supposed to read a directory and capture all rds files. It is running fine. But when a new rds file is coming into directory from where app suppose to read, it's not able to read new file. When I touch server.R then app is able to capture new file as well.
So long story in short, whenever a new file is coming into directory, I need to to touch server.R file to work as latest content. I am not making any changes in server.R. To execute successfully I need to run "touch server.R". has someone seen this before?
I am not able to understand, server.R needs any change in time stamp to run successfully.
Thanks!
Tinku
# MrFlick - No I haven't hard coded anything in server.R file. Actually same code is working on other server. I just copied the same program from test to qa box and not it changed the behavior. If I touched the server.R file and refresh the browser then it is working fine. Very starange for me!
#jdharrison - Thanks for your suggestion. But this (my existing server.R) code is running fine on dev server but when I moved to QA, then it not running as expected. I am surprised, that what touch or any non significant change in server.R is enabling it to run fine for one time.
Actually server.R code is reading the .RDS files from the directory and displaying in drop down list. it is working fine on dev server. But on QA server, if I am deleting or creating any new .RDS file then it's not displaying in drop down list automatically, until I touch the server.R file.

You can use a reactivePollto periodically check the directory you are interested in. In this example an actionButton allows the user to add a file to a test directory. The test directory is polled every second by the app and a table with file info is displayed:
library(shiny)
dir.create('test', showWarnings = FALSE)
write(1:3, 'test/dumfile.txt')
write(1:3, 'test/dumfile2.txt')
readTimestamp <- function() Sys.time()
valueFunc <- function() {
print(readTimestamp())
out <- lapply(list.files('test', full.names = TRUE), file.info)
do.call(rbind.data.frame, out)
}
runApp(list(
ui = bootstrapPage(
actionButton("addFile", "Add a file!"),
tableOutput('myTable')
),
server = function(input, output, session) {
observe({
if(input$addFile > 0){
write(1:3, tempfile('file', 'test', '.txt'))
}
})
dirData <- reactivePoll(1000, session, readTimestamp, valueFunc)
output$myTable <- renderTable({
myData <- dirData()
myData
})
}
))

Related

List of file paths to iteratively pass through sourced python function in Shiny

I have come up with a python function that I have confirmed works just fine. I am trying to put this into a Shiny app using Shiny's reticulate. I am not super familiar with Shiny but need to use it anyhow.
To give a bit of background on what I am doing, I've written some python code that takes takes multiple files and matches strings based on one common list of strings. This code works fine when I run the python files on my machine.
I need to make this available to others using a shiny app, where they can upload their files, then have the app run the underlying python code.
So far, I have set up the shiny app so that it can take in multiple files. I am having a hard time thinking about how I can use reactive to make a list of the file path names to then send to my python code (which includes a step to open and read the file) so it can do its thing.
This is the code that I have for my app thus far:
library(shiny)
library(shinyFiles)
# define UI
ui <- fluidPage(
titlePanel('Counter of Gendered Language'),
fileInput("upload", "Choose a folder",
multiple = TRUE,
accept = c('text')),
tableOutput('text'),
downloadButton('output', 'Download Count File .csv'))
# define server behavior
server <- function(input, output){
# Setup
#* Load libraries
library(reticulate)
#* Use virtual environment for python dependencies
use_virtualenv('file/path/py_venv', required = TRUE)
#* Source code
source_python('code/counting_gendered_words.py')
#* Load list of words to match raw text against
dictionary <- read.csv('data/word_rating.csv')
text <- reactive(
list <- list.files(path = input$upload[['name']])
)
output$counted <- gendered_word_counter(dictionary, text())
output$downloadData <- downloadHandler(
filename = function(){
paste0(input$upload, ".csv")
},
content = function(file){
vroom::vroom_write(text$counted, file)
}
)
}
# Run the application
shinyApp(ui = ui, server = server)
What it tells me when I run this app is that:
Error : Operation not allowed without an active reactive context.
You tried to do something that can only be done from inside a reactive consumer.
So what I am wanting to do is basically just pass each file name that someone uploads to the app and pass that file's name into my gendered_word_counter() python function.
How would I go about this?
I'm super confident that I just am being a newbie and it is probably a super simple fix. Any help from those who are more comfortable with Shiny would be much appreciated!
Edit: I notice that my code is only calling the names of the files which is meaningless for me without the contents of the uploaded files! Would it be better if I read the files in the shiny app instead of in my .py file?
I can't reproduce the app without the python code, but i can see that this line:
output$counted <- gendered_word_counter(dictionary, text())
has a reactive object (text()) being called with no reactive context. It should be wrapped in observe or observeEvent.
observe({
output$counted <- gendered_word_counter(dictionary, text())
})
Also let's add the parenthesis here:
content = function(file){
vroom::vroom_write(text()$counted, file)
}

Rendering A Local Image File in Shiny

I am trying to render a local image file onto the Shiny app interface using a snippet of the example code provided by Shiny website below:
ui <- fluidPage(
imageOutput("plot3")
)
server <- function(input, output, session) {
# Send a pre-rendered image, and don't delete the image after sending it
# NOTE: For this example to work, it would require files in a subdirectory
# named images/
output$plot3 <- renderImage({
filename <- normalizePath(file.path('./images',
paste('image', '2', '.jpeg', sep='')))
# Return a list containing the filename
list(src = filename, alt = "Alternate text")
}, deleteFile = FALSE)
}
shinyApp(ui, server)
It didn't work when I ran the application. However when I added back the interactive() function that was originally in the example code, encase the main code body, I was able to display the local image file without any problems.
if (interactive()) {
ui <- fluidPage(
imageOutput("plot3")
)
server <- function(input, output, session) {...
}
This puzzles me as many of Shiny's tutorials and demonstrations showed rendering can be done without encasing the code body in a scope.
Is there anyone who encounter a similar scenario such as this? Rendering a local image file into a Shiny app?
I just discovered what was wrong with the code through trial and error. The directory which the shiny code app is saved in a different location from the location where the image file is saved. So the solution is either to place a setwd([www image folder location]) or relocate image folder www to where the shiny app resides which it worked - the image is successfully rendered.

R shiny save a file path for next session

I've been making an app in shiny, and it is meant to use/edit the same file for multiple different people.
The idea is that when you open the app for the first time, it'll prompt you to select the file, and save the location of the file so you don't have to select it every time you open the program.
I can't seem to find a way to do this, only saving edits to the file. Is there a way, or would you just have to select the file every time?
EDIT: here is some simple code to give you an idea of what i've been working with
library(shiny)
setwd("~/myfiles")
ui <- fluidPage(
fileInput("user_file", "Please enter a file"),
textOutput("txt_param")
)
server <- function(input, output, session) {
file_path <- input$user_file$datapath
output$txt_param <- renderText(as.character(input$user_file$datapath))
### Store the file's path in a csv to access later ###
as.data.frame(file_path)
write.csv(file_path, "user_file_path.csv")
}
shinyApp(ui, server)

Not able to run external R script from end user local library into Shiny app(shinyapp.io)

UPDATED
I created one shiny app. there end user can run their Function(R Script). I enabled those things over this function(below)
server.R
observeEvent(input$v1,{
inFile <- input$v1
if (is.null(inFile))
return(NULL)
})
ui.R
fileInput('v1', 'End user function only in R script',accept=c('R/ R script','.R'))
above both codes are only small pieces. i want to run my separate R file over browsing Here that codes are not sourced. i want to get that function inside my shiny app and plot in my graph.
My problem is whole things working normally in my local host, I deployed this same app in shinyapp.io after that the end user part is not working(not whole app)
I am stuck with this past three days!
Guys is it possible to do?? Can any one help me??
I hope you Guys understand this. if not sorry!!!
Thanks in advance
I found the answer my self:
Include load() function in server page and get sourced the external file over load button.
inside the server code like this.
load_Rdata <- function(){
if(is.null(input$file)) return(NULL)
inFile <- isolate({ input$file })
source(inFile$datapath)
}
call this function inside the observe event
observeEvent(input$btnLoad,{
load_Rdata()
}) `
UI code like this
fileInput("file", label = "Rdata"),
actionButton(inputId="btnLoad","Load")
get the file over fileInput and source the file using load button to call load_Rdata to source file..

Download handler does not save file shiny R

library(shiny)
library(plyr)
shinyServer(function(input, output){
myfile<-reactive({
#reading 3 csv files and merging them into a dataframe
})
output$downloadData<-downloadHandler(
filename = function(){
paste("mergedfile","csv",sep='.')
},
content= function(file){
write.csv(myfile(),file,sep=",")
}
)
})
I am reading 3-4 files reactively and then merging them. After that without displaying them I need to download the merged file.
I wrote the above code but a dialog box opens which asks me where to save but the file doesn't get saved. Am I doing something wrong with the download handler.
ui.R
downloadButton('downloadData','Download')
This is what I have in my main panel in ui.R file
Your probably using the Rstudio viewer to run the app? Open the app in your browser and your code will work
( click open in borwser or run runApp('/path/to/myApp',launch.browser=T) ).
See this link.
Also no need to set sep="," for write.csv since this is the default.

Resources