R shiny updateSelectInput in observeEvent not working - r

In my Shiny app my users can upload a file from the server to view the results. I have the user select the file using a selectInput, and then they click an actionButton to load the file. I also want users to be able to delete files and add new files, and I've set that up successfully using separate actionButtons. When the user deletes or adds a file I want to update the selectInput so the deleted files aren't there anymore, and the added files are. I tried this using updateSelectInput in my observeEvent code but its not working. Here's my observeEvent for the delete file portion:
#Delete parameter files
observeEvent(input$delete,{
file.remove(input$input_file) #deletes the file selected in the input_file widget
choices <- list.files("C:/Users/shiny/testapp/", pattern="*.Rdata")
updateSelectInput(session,"input_file",choices) #supposed to update the input_file widget
})
When I run the app with this code in it, two things happen. In the App window, I get this text right above the input_file widget: [object Object
And in my R console I get:
Input to asJSON(keep_vec_names=TRUE) is a named vector. In a future
version of jsonlite, this option will not be supported, and named
vectors will be translated into arrays instead of objects. If you want
JSON object output, please use a named list instead. See ?toJSON.
I have included the session parameter in my shinyServer call:
shinyServer(function(input, output, session)
Any advice would be appreciated.

I found a corner case that also causes this bug. Upon putting tabPanel() in a renderUI(), an updateSelectInput in an unrelated area of my code just stopped working.
To resolve, leave the tabPanel in ui.R, and use renderUI() to adjust within the function instead of bringing it all into server.R, like here: updateSelectInput order of operations/race condition

Related

Run multiple render functions on user uploaded file simultaneously in R shiny

I have multiple render functions within the R shiny code performing independent tasks (multiple output plots) on the user uploaded file. I would like all these render functions to start running in parallel when the user uploads the file. How could I do that in R shiny?
You can use reactive with file upload button to store a data, and call it in every renderPlot function :
And you should paste your code what you have done so far on Stack Overflow, it will be more easier to help:
df<-reactive({ read.csv(path) })
# call the csv file with df() rather than df when you use reactive to store it
output$plot1<-renderPlot({plot(df()[,1])})
output$plot2<-renderPlot({plot(df()[,2])})
Something like this

How to split Shiny app code over multiple files in RStudio? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I tried to split code for a shiny application over different files, but can't get this to work decently in Shiny. My attempt can be found in this demo
How can I split up my code over different files, but still keep the 'Run App button ' and have 'Code Completion' back in RStudio?
if not ! can i integrate shiny with Visual Studio ?
Yes, you can achieve that very easily in the same way you do that with every other project in RStudio: by using the R mechanisms provided to achieve that:
define functions and/or objects in separate files.
use source() in your main file to load their definitions
Code completion for shiny functions only occurs in RStudio when the shiny package is loaded using library(shiny). The 'Run App' button will be visible for the main file in the application. In the example below, that would be the app.R file. So if you want to run your app from within RStudio, you always have to go back to the main file.
standard example
An example :
In a file app.R you put:
library(shiny)
source('myUI.R', local = TRUE)
source('myServer.R')
shinyApp(
ui = myUI,
server = myserver
)
This code does nothing else but initiate the objects myUI and myserver and call the app.
The file myUI.R contains
source('Tabs.R')
myUI <- shinyUI({
fluidPage(
tabsetPanel(
Tab1,
Tab2
)
)
})
This file defines the UI object used in app.R. The function tabsetPanel takes a number of tabPanels as arguments. These tabPanels are created in the following file (Tabs.R), so that one has to be sourced before the UI is constructed.
The file Tabs.R contains:
Tab1 <- tabPanel("First Tab",
selectInput("select",
"Choose one",
choices = letters[1:3],
selected = 'a'))
Tab2 <- tabPanel("Second Tab",
textOutput('mychoice'))
This file creates the tabPanel objects to be added to the tabsetPanel. In my own code, I store every tabPanel definition in a separate file.
The file myServer.R contains:
myserver <- function(input,output,session){
output$mychoice <- renderText(
input$select
)
}
And if you want, you can again create separate files with functions that can be used inside the server function. But you always have to follow the classic R logic: assign things to an object and refer to that object at the position you want to insert it.
You can also source code directly inside the server() function. In that case you should source locally using source(..., local = TRUE), so the created objects are contained inside the server function. See also : https://shiny.rstudio.com/articles/scoping.html
Using modules
If you want to take it up a notch and reuse a certain logic and layout (eg a plot option control panel that should be attached to some plots), you should go to modules. (see also http://shiny.rstudio.com/articles/modules.html )
Modules can again be stored in a separate file, and that file sourced in the app.R file you have.
#Joris Meys 's answer covered the topic of splitting shiny code into files. Though one part of the question is to use the run app button, which may not be available even if the organization make a valid shiny app.
If you search this question you can find this issue, then following to the commit made in that issue you can find what's the rule to have a run app button, and this function about isShinyAppDir, this function of shinyfiletype:
Basically any folder have ui.R, server.R, app.R, global.R, www folder will be considered as shiny folder(the detailed conditions are more complex, see source code), then the above 4 files will have run app button.
One thing I noticed is that usually you can keep the app running, make some changes then reload app to see the changes, but if you sourced other file, reload app button will not reload changes in that sourced file.

R Shiny: 'error cannot open the connection'

so I have a Shiny app where I'm trying to read in a user-identified input file.
Towards that end, my ui.R has the line fileInput("predictor2", label = "Predictor Values") and I try to read the file using the line predictor <- read.delim("input$predictor2") in my server.R file.
However, I get a message saying Error: Cannot open the connection. If I don't try to read in the file and use another matrix of values, the code works fine. Any advice for how to fix this problem or more detail that would be useful?
You code is looking for a file with the literal name input$predictor2 which presumably does not exist. You first need to remove the quotes from around it, then add which column of the return actually has the path to the data, e.g.:
read.delim(input$predictor2$datapath)
See the help for fileInput for an example that checks to make sure something has been uploaded first.

Web application which runs R

I have written my R script with some functions to do some calculations. On the output of my calculations, I have created plots in shiny(4 tab panels in that as of now, which is using the data specified in my global.R). Now I am trying to automate the process and deliver it to non technical users. So something like, users feed in 2 csv files in web UI and click a button in the web UI, which will then call my r scripts to do the calculations, then my server.R script should build plots on the output of it. Any similar examples? I tried different links, but nothing seems to be relevant.
If I add my R script using source(**.R) and use the functions mentioned in there. Or Do I still have to save output in data folder and specify something in global.R or just use the output of the function in my plot construction?
If I have the fileInput option in first tab in my tabpanels, how can I make stop the user from viewing the other tabs(tabs with graphs) without loading the input csv files and clicking the "Go" button?
Can I do this whole thing in Shiny ? Or better to go for rook or some other framework which calls my r script just for calculations?

How to validate the file type of a file uploaded by the user in a Shiny app?

I'm trying to create a Shiny App (using R Studio).
I want to use a fileInput widget (named ffile) to read an xlsx or xls file from the user. However, I need it to make sure that it's the correct file type, otherwise the rest of the code will not work. I read about the validate() and need() functions. So I did it like this:
data<-reactive({
infile = input$ffile
if (is.null(infile))
return(NULL)
ext<-c('application/vnd.ms-excel','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
o<-is.element(infile$type,ext)
validate(need(o,'Wrong ext. Select .xls, .xlsx or .csv'))
file<-read.xlsx(infile$datapath, 1)
return(file) })
I tried loading a .docx document and it was successfully blocked and the warning message was displayed as desired. However, when I try to load a correct .xlsx file it would still show the warning message instead of actually accepting it. I do not know if I'm using the validate/need incorrectly or there is something about MIMEs that I don't quite understand. Help would be appreaciated.
You can set the accepted MIME directly in the fileInput object in your ui.R using the accept argument:
fileInput('file1', 'Choose CSV File',
accept=c('application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'.xls',
'.xlsx'))
This will only let the user select excel files from the file browser window that opens.
In your server.R, you can then just get the data from the file without validating.

Resources