i have some problem with fileInput for R Shiny. Size limit is set to 5MB per default.
Since the files i have to work with are very large (>50GB), I only need the datapath and or name of the file. Unfortunatly fileInput wants to upload the complete file or at least it is loading the file somehow and tells me that the file is too big after i have reached the 5MB limit.
How can I only hand over the path to my app without uploading the file?
ui.R
library(shiny)
# Define UI ----
shinyUI(fluidPage(
h1("SAS Toolbox"),
tabsetPanel(
tabPanel("SASFat",
sidebarPanel(h2("Input:"),
actionButton("runSASFat","Run Job",width="100%",icon("paper-plane"),
style="color: #fff; background-color: #337ab7; border-color: #2e6da4"),
wellPanel(
#tags$style(".shiny-file-input-progress {display: none}"),
fileInput("FEInp","Pfad FE input Deck:"),
fileInput("FERes","Pfad FE Results:")
),
wellPanel(
checkboxGroupInput("options1","Auswertung:",c("Grundmaterial","Schweissnähte")),
conditionalPanel(condition="$.inArray('Schweissnähte',input.options1) > -1",
sliderInput("filter", "Filter:", 0.75, min = 0, max = 1))
),
wellPanel(
radioButtons("solver", "Solver:", c("Ansys","Abaqus", "Optistruct")),
conditionalPanel(condition="input.solver == 'Ansys'",selectInput("lic", "Lizenz",c("preppost","stba","meba")))
),
wellPanel(
checkboxGroupInput("options2","Optionen:",c("Schreibe LCFiles"))
)
),
mainPanel(br(),h2("Output:"),width="30%")
),
tabPanel("Nietauswertung"),
tabPanel("Spannungskonzept EN12663")
)
))
server.R
# Define server logic ----
shinyServer(function(input, output) {
observeEvent(input$runSASFat, {
FEInp <- input$FEInp
FERes <- input$FERes
opt1 <- input$options1
opt2 <- input$options2
filter <- input$filter
solver <- input$solver
lic <- input$lic
write(c(FEInp$datapath,FERes$datapath,opt1,opt2,filter,solver,lic),"ghhh.inp")
})
})
Thanks in advance
Michael
Thanks for the example #MichaelBird. I adapted your code to let users cancel the request without choosing a file (your app crashed after canceling):
This by the way only works on the PC hosting the shiny app.
library(shiny)
ui <- fluidPage(
titlePanel("Choosing a file example"),
sidebarLayout(
sidebarPanel(
actionButton("filechoose",label = "Pick a file")
),
mainPanel(
textOutput("filechosen")
)
)
)
server <- function(input, output) {
path <- reactiveVal(value = NULL)
observeEvent(input$filechoose, {
tryPath <- tryCatch(
file.choose()
, error = function(e){e}
)
if(inherits(tryPath, "error")){
path(NULL)
} else {
path(tryPath)
}
})
output$filechosen <- renderText({
if(is.null(path())){
"Nothing selected"
} else {
path()
}
})
}
shinyApp(ui = ui, server = server)
An alternative way would be to increase the maximum file size for uploads:
By default, Shiny limits file uploads to 5MB per file. You can modify
this limit by using the shiny.maxRequestSize option. For example,
adding options(shiny.maxRequestSize = 30*1024^2) to the top of app.R
would increase the limit to 30MB.
See this RStudio article.
Here is an example of using file.choose() in a shiny app to obtain the local path of the file (and hence the file name):
library(shiny)
ui <- fluidPage(
# Application title
titlePanel("Choosing a file example"),
sidebarLayout(
sidebarPanel(
actionButton("filechoose",label = "Pick a file")
),
mainPanel(
textOutput("filechosen")
)
)
)
server <- function(input, output) {
path <- reactiveValues(
pth=NULL
)
observeEvent(input$filechoose,{
path$pth <- file.choose()
})
output$filechosen <- renderText({
if(is.null(path$pth)){
"Nothing selected"
}else{
path$pth
}
})
}
# Run the application
shinyApp(ui = ui, server = server)
Is this what you're after?
Related
I have a shiny app that saves a few variables globally. I would like for the user to be able to click a button 'Run' That would 1) save the variables globally and 2) run an R script that uses those variables.
Below is where I am at, but I am not able to save the variables before hitting the button.
library(shiny)
ui <- fluidPage(
column(4, wellPanel(dateInput('date', label = 'Date input: yyyy-mm-dd', value = Sys.Date()))),
column(4, wellPanel(numericInput('STD', 'STD', 1.2))),
actionButton("Run", "Run the tool")
)
server <- function(input, output) {
observeEvent(input$STD, {
STDShiny <<- input$STD1
})
observeEvent(input$date, {
dateShiny <<- input$date
})
observeEvent(input$Run, {
source("someScript.R")
})
}
Example script: someScript.R
dir.create(paste(date,STD, sep = ''))
Any assistance is appreciated.
Somescript.R code:
dir.create(paste(.GlobalEnv$dateShiny, .GlobalEnv$STDShiny, sep = ''))
Shinyapp:
library(shiny)
library(tidyverse)
ui <- fluidPage(
column(4, wellPanel(dateInput('date', label = 'Date input: yyyy-mm-dd', value = Sys.Date()))),
column(4, wellPanel(numericInput('STD', 'STD', 1.2))),
actionButton("Run", "Run the tool") #The button to trigger script
)
server <- function(input, output) {
#Upon clicking in the button the following code gets executed
observeEvent(input$Run,{
#declare as variables in the global env with the values of the inputs
walk2(c('STDShiny', 'dateShiny'), c(input$STD, input$date), ~{
assign(..1, ..2, envir = .GlobalEnv)
})
#Run the script
exec(source, file = 'someScript.R')
})}
shinyApp(ui, server)
I am trying to return a dynamic code chunk in R as part of a shiny app. A simple example of what I am trying to do is,
library(shiny)
runApp(list(
ui = bootstrapPage(
sliderInput("mu", "Mean", min=-30, max=30, value=0, step=0.2),
uiOutput('chunk')
),
server = function(input, output) {
output$chunk <- renderUI({
HTML(markdown::markdownToHTML(text=paste0("```{r}",
"\n dnorm(0, ", input$mu,", 2)"),
options=c("highlight_code"))) })
}
))
This produces an unformatted code chunk. I would like to be able to use pygments/another-solution to highlight this code, and also python/other-language code which will form part of a web app.
Any ideas?
Additional Languages
Here's a solution that works for highlighting many different languages. It's based on this answer, which uses Prism. We load the Prism dependencies and then load dependencies for each language we want to highlight.
## from: https://stackoverflow.com/a/47445785/8099834
## get prism dependencies
prismDependencies <- tags$head(
tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/prism/1.8.4/prism.min.js"),
tags$link(rel = "stylesheet", type = "text/css",
href = "https://cdnjs.cloudflare.com/ajax/libs/prism/1.8.4/themes/prism.min.css")
)
prismLanguageDependencies <- function(languages) {
lapply(languages, function(x) {
tags$head(
tags$script(
src = paste0("https://cdnjs.cloudflare.com/ajax/libs/prism/1.8.4/components/prism-",
x, ".min.js")
)
)
})
}
## format code with tags and language
prismAddTags <- function(code, language = "r") {
paste0("<pre><code class = 'language-", language, "'>",
code,
"</code></pre>")
}
prismCodeBlock <- function(code, language = "r") {
tagList(
HTML(prismAddTags(code, language = language)),
tags$script("Prism.highlightAll()")
)
}
## run app
library(shiny)
runApp(list(
ui = bootstrapPage(
prismDependencies,
prismLanguageDependencies(c("sql", "r", "python")),
sliderInput("mu", "Mean", min=-30, max=30, value=0, step=0.2),
uiOutput('r_chunk'),
uiOutput('python_chunk'),
uiOutput('sql_chunk')
),
server = function(input, output) {
output$r_chunk <- renderUI({
prismCodeBlock(
code = paste0("# this is R code\ndnorm(0, ", input$mu,", 2)"),
language = "r"
)
})
output$python_chunk <- renderUI({
prismCodeBlock(
code = '# this is python code
# Say hello, world.
print ("Hello, world!")',
language = "python"
)
})
output$sql_chunk <- renderUI({
prismCodeBlock(
code = "-- this is SQL code
SELECT * FROM mytable WHERE 1=2",
language = "sql"
)
})
}
))
Updated Answer
As pointed out in the comments, the original answer doesn't work. Turns out getting the highlighting to work takes a little more effort.
Fortunately, someone has already figured it out! They have written two functions: renderCode for the server and outputCode for the ui which seem to work well. The package is here and the relevant functions are here.
Here's an example:
## install the package
library(devtools)
install_github("statistikat/codeModules")
## run the app
library(codeModules)
library(shiny)
runApp(list(
ui = bootstrapPage(
sliderInput("mu", "Mean", min=-30, max=30, value=0, step=0.2),
codeOutput('chunk')
),
server = function(input, output) {
output$chunk <- renderCode({
paste0("dnorm(0, ", input$mu,", 2)")
})
}
))
Original Answer -- Doesn't work
highlight.js will format your code and is included in shiny. Per this answer, it supports 169 languages at this time.
You just need to tag your code. Try something like this:
library(shiny)
highlightCode <- function(code) {
HTML(
paste0("<pre><code class='html'>",
code,
"</code></pre>")
)
}
runApp(list(
ui = bootstrapPage(
sliderInput("mu", "Mean", min=-30, max=30, value=0, step=0.2),
uiOutput('chunk')
),
server = function(input, output) {
output$chunk <- renderUI({
highlightCode(paste0("dnorm(0, ", input$mu,", 2)"))
})
}
))
I am developing an application in shiny.In shiny, I am rendering a simple plot using the action button. I have included a download button to download the the plot that is now in UI. from my code(plot3)
I tried the below code, to save the image, but I am getting an error
plotInput not found.
Could any one suggest where i am going wrong.
Below is my code for reference.
UI:
ui <- tabItem(tabName = "models2",
fluidPage(
fluidRow(
infoBoxOutput("overview")
),
fluidRow(
actionButton("result1","Generate Result"),
downloadButton('downloadPlot','Download Plot'),
plotOutput("plot3")
)
))
SERVER
server <- function(input,output,session{
output$overview <- renderValueBox({
valueBox(
paste("91"),"Overview",icon=icon("hourglass"),
color="green"
)
})
observeEvent(input$result1,{
output$plot3 <- renderPlot({
ggplot(data=timedata, aes(x=dat1, y=yes, group=3))+
geom_point(shape=1)+
coord_cartesian(xlim=c(dat1_xlowlim,dat1_xhighlim))+
labs(title="Probability",x="Date",y="True probability")
})
})
output$downloadPlot <- downloadHandler(
filename = function(){paste(input$plot3,'.png',sep='')},
content = function(plot3){
ggsave(plot3,plotInput())
}
)
})
Also, to note my shiny and R studio are in R environment.
library(shiny)
library(shinydashboard)
ui <- tabItem(tabName = "models2",
fluidPage(
fluidRow(
infoBoxOutput("overview")
),
fluidRow(
actionButton("result1","Generate Result"),
downloadButton('downloadPlot','Download Plot'),
plotOutput("plot3")
)
))
server <- function(input,output,session){
output$overview <- renderValueBox({
valueBox(
paste("91"),"Overview",icon=icon("hourglass"),
color="green"
)
})
data <- reactiveValues()
observeEvent(input$result1,{
data$plot <- ggplot(data=iris, aes(x=Sepal.Length, y=Sepal.Width))+
geom_point(shape=1)})
output$plot3 <- renderPlot({ data$plot })
output$downloadPlot <- downloadHandler(
filename = function(){paste("input$plot3",'.png',sep='')},
content = function(file){
ggsave(file,plot=data$plot)
}
)
}
shinyApp(ui, server)
#Mikz
I don't have enough reputation to follow your comment. Thus, I create a new anwser but wish to answer your question 'why app closes automatically?'.
I had same issue when I develop shiny app on rstudio-server of my company. My app will close by itself after a while. However, same app run on my local laptop don't have this issue.
After my research, I believe it caused by timeout setting (default is 60 seconds). I also use function ~~Sys.sleep()~~ to test this default time. I found the solution works for me from this blog .
The idea is using WebSocket to trigger app every 50 seconds. In this way, you don't need to ask technique guy to adjust setting on server level.
I would ask. Does Shiny do like always-refreshing the code after input ?
First I code this in ui :
box( ##title="Quality Attributes",
selectInput("att_ViewChart", width = '100%',label="Quality Attributes",
##multiple = TRUE,
choices=list(
"-",
"Suitability",
"Security",
)
)
),
dataTableOutput("tabelstatus")
Then I code this in server :
server = function(input, output) {
withProgress(message = "AAAAA",{
DateStatus_Sui<-c(1,2,3,4,NA,5,6,NA,7)
TimeStatus_Sui<-c(11,22,33,44,NA,55,66,NA,88)
status_Sui<-c(11,22,44,55,66,77,88)
jumlah<-7
})
if(input$att_ViewChart=="Suitability"){
Date<-DateStatus_Sui[!is.na(DateStatus_Sui)]
Time<-TimeStatus_Sui[!is.na(TimeStatus_Sui)]
Status<-status_Sui
Observation<-1:jumlah
#output
tabelstatus<-data.frame(Observation,Date,Time,Status)
output$tabelstatus<-renderDataTable(tabelstatus)
}
I hope when I run the app. Shiny will process the code (shown by progress bar 'AAAAA') And after that, if I choose Suitability it will do a little more process and then show the table . But I found that the progress bar appears again. Seems to me it re-runs the code from the beginning. How to fix this? Thank you
In the abscence of a fully reproducible example, I'm guessing this is what you're trying to do (i.e, make the table reactive according to your input$att_ViewChart):
library(shiny)
library(shinydashboard)
ui <- dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody(
box( selectInput("att_ViewChart", width = '100%',label="Quality Attributes",
choices=c("-","Suitability","Security"))),
dataTableOutput("tablestatus")
)
)
server = function(input, output) {
withProgress(message = "AAAAA",{
DateStatus_Sui<-c(1,2,3,4,NA,5,6,NA,7)
TimeStatus_Sui<-c(11,22,33,44,NA,55,66,NA,88)
status_Sui<-c(11,22,44,55,66,77,88)
jumlah<-7
})
## make your table reactive on `input$att_ViewChart`
output$tablestatus <- renderDataTable({
if(input$att_ViewChart=="Suitability"){
Date<-DateStatus_Sui[!is.na(DateStatus_Sui)]
Time<-TimeStatus_Sui[!is.na(TimeStatus_Sui)]
Status<-status_Sui
Observation<-1:jumlah
tablestatus <- data.frame(Observation,Date,Time,Status)
}else{
tablestatus <-data.frame()
}
return(tablestatus)
})
}
shinyApp(ui = ui, server = server)
I have a static png file of several thousand pixels height and width, and I would like to visualize parts of if by interactively zooming in and out of it in an RStudio Shiny website. What is the best way to have this working in a way that is relatively well performing?
You can use any of a number of javascript libraries. I chose https://github.com/elevateweb/elevatezoom to use in this example:
library(shiny)
runApp(
list(ui = fluidPage(
tags$head(tags$script(src = "http://www.elevateweb.co.uk/wp-content/themes/radial/jquery.elevatezoom.min.js")),
actionButton("myBtn", "Press Me for zoom!"),
uiOutput("myImage"),
singleton(
tags$head(tags$script('Shiny.addCustomMessageHandler("testmessage",
function(message) {
$("#myImage img").elevateZoom({scrollZoom : true});
}
);'))
)
)
, server = function(input, output, session){
output$myImage <- renderUI({
img(src = "http://i.stack.imgur.com/RWd7T.png?s=128&g=1", "data-zoom-image" ="http://i.stack.imgur.com/RWd7T.png?s=128&g=1")
})
observe({
if(input$myBtn > 0){
session$sendCustomMessage(type = 'testmessage',
message = list())
}
})
}
)
)