I experienced an unexpected behavior of my R shiny code and I'm asking myself if this is bug or if I don't understand how req() works.
I have an app where the user first uploads a *.txt file containing data with a location id, a date, and other data. Then the user has to choose two numerical values. The data is checked for NAs in the col date. If there are no NAs a text should appear telling the user everything is fine.
Below are two versions of my code. In output$txt <- renderText({ I use req() to test if all inputs are set and the file is loaded.
The differences between the two codes are the ordering of the last two arguments in req. Whereas in the first version, the green text appears already when both numeric inputs are set even the file is not uploaded, the second code behaves as expected; the user has to choose the numeric value and has to choose a file before the green bar with text appears.
Why makes the ordering of the arguments in req() a difference?
Code 1:
library(shiny)
library(lubridate)
# UI
ui <- fluidPage(
fluidRow(
column(4,
wellPanel(
fileInput("file1", label = h4("file upload")),
numericInput("in1", label = h4("first input"),value = 2.5, step=0.5),
numericInput("in2", label = h4("second input"),value = NULL, step=0.5)
)
),
column(8,
h4(textOutput("txt"), tags$style(type="text/css", "#txt {vertical-align:top;align:center;color:#000000;background-color: #4cdc4c;}")),
h2(""),
textOutput("fileinfo"),
tableOutput("tab_data")
)
)
)
# SERVER
server <- function(input, output) {
output$txt <- renderText({
req(input$in1, input$in2, fl_data(), input$file1)
"your data is ok and you have chosen input 1 and 2"
})
fl_data <- reactive({
validate(
need(input$file1 != "", "upload data and choose input 1 and 2...")
)
inFile <- input$file1
if (is.null(inFile)) {
return(NULL)
} else {
dd <- read.table(inFile$datapath, sep=";", stringsAsFactors=FALSE, header=TRUE)
dd[,2] <- ymd(dd[,2])
if (sum(is.na(dd[,2]))>0) dd <- NULL
}
})
output$tab_data <- renderTable({head(fl_data()[,1:4])})
output$fileinfo <- renderPrint({input$file1})
}
# Run the application
shinyApp(ui = ui, server = server)
Code 2:
library(shiny)
library(lubridate)
# UI
ui <- fluidPage(
fluidRow(
column(4,
wellPanel(
fileInput("file1", label = h4("file upload")),
numericInput("in1", label = h4("first input"),value = 2.5, step=0.5),
numericInput("in2", label = h4("second input"),value = NULL, step=0.5)
)
),
column(8,
h4(textOutput("txt"), tags$style(type="text/css", "#txt {vertical-align:top;align:center;color:#000000;background-color: #4cdc4c;}")),
h2(""),
textOutput("fileinfo"),
tableOutput("tab_data")
)
)
)
# SERVER
server <- function(input, output) {
output$txt <- renderText({
req(input$in1, input$in2, input$file1, fl_data())
"your data is ok and you have chosen input 1 and 2"
})
fl_data <- reactive({
validate(
need(input$file1 != "", "upload data and choose input 1 and 2...")
)
inFile <- input$file1
if (is.null(inFile)) {
return(NULL)
} else {
dd <- read.table(inFile$datapath, sep=";", stringsAsFactors=FALSE, header=TRUE)
dd[,2] <- ymd(dd[,2])
if (sum(is.na(dd[,2]))>0) dd <- NULL
}
})
output$tab_data <- renderTable({head(fl_data()[,1:4])})
output$fileinfo <- renderPrint({input$file1})
}
# Run the application
shinyApp(ui = ui, server = server)
req short-circuits, just like the && and || operators. As soon as it comes across an unavailable value (args evaluated left-to-right), it stops the reactive chain and doesn't care about any further args.
In the second example, input$file1 prevents fl_data() from ever executing if missing, so the validation in fl_data never occurs. But rather than order the req args like in the first example, I would just remove the check for input$file1 in output$txt, as it's already being checked in fl_data.
Related
I'm trying to create a shiny dashboard that allows the user to select a csv file. The file contains only two columns that are order number and dateCreated. I want the user to be able to in addition, select the date range that they desire and get a summary count statistic.
So far my code is as follows:
library(shiny)
library(plotly)
library(colourpicker)
library(ggplot2)
ui <- fluidPage(
titlePanel("Case Referrals"),
sidebarLayout(
sidebarPanel(
fileInput("file", "Select a file"),
sliderInput("period", "Time period observed:",
min(data()[, c('dateCreated')]), max(data()[, c('dateCreated')]),
value = c(min(data[, c('dateCreated')]),max(data()[, c('dateCreated')])))
),
mainPanel(
DT::dataTableOutput("table")
)
)
)
# Define the server logic
server <- function(input, output) {
# file input
input_file <- reactive({
if (is.null(input$file)) {
return("")
}
})
# summarizing data into counts
data <- input_file()
data <- subset(data, dateCreated >= input$period[1] & dateCreated <= input$period[2])
output$table <- DT::renderDataTable({
data
})
}
shinyApp(ui = ui, server = server)
I get an error message saying:
Error in data()[, c("dateCreated")] : incorrect number of dimensions
Can anyone help me understand what the problem might be and/or provide a better framework for doing this? And to be clear in the csv file, the createDate variable is broken down into individual days for when the order was placed.
Thank you!
I added comments to the faulty steps.
library(shiny)
ui <- fluidPage(
titlePanel("Case Referrals"),
sidebarLayout(
sidebarPanel(
fileInput("file", "Select a file"),
# you cannot call data() in your ui.
# You would have to wrap this in renderUI inside of your server and use
# uiOutput here in the ui
sliderInput("period", "Time period observed:", min = 1, max = 10, value = 5)
),
mainPanel(
DT::dataTableOutput("table")
)
)
)
# Define the server logic
server <- function(input, output) {
input_file <- reactive({
if (is.null(input$file)) {
return("")
}
# actually read the file
read.csv(file = input$file$datapath)
})
output$table <- DT::renderDataTable({
# render only if there is data available
req(input_file())
# reactives are only callable inside an reactive context like render
data <- input_file()
data <- subset(data, dateCreated >= input$period[1] & dateCreated <= input$period[2])
data
})
}
shinyApp(ui = ui, server = server)
i have a question regarding Shiny and the usage of Data frames.
I think i understood that i need to create isolated or reactive environmentes to interact with, but if i try to work with the Dataframe i get an error message:
Error in pfData: konnte Funktion "pfData" nicht finden
i tried to manipulate the dataframe by this code:
server <- function(input, output) {
observeEvent(input$go,
{
pf_name <- reactive({input$pfID})
pf_date <- reactive({input$pfDate})
if (pf_name()!="please select a PF") {
pfData <- reactive(read.csv(file =paste(pf_name(),".csv",sep=""),sep=";",dec=","))
MDur <- pfData()[1,15]
pfData <- pfData()[3:nrow(pfData()),]
Total = sum(pfData()$Eco.Exp...Value.long)
}
})
}
If i manipulate my Dataframe in the console it works just fine:
pfData <- pfData[3:nrow(pfData),]
Total = sum(pfData$Eco.Exp...Value.long)
Assets = sum(as.numeric(gsub(",",".",gsub(".","",pfData$Value,fixed=TRUE),fixed=TRUE)))
pfData$Exposure <- with(pfData, Eco.Exp...Value.long /Total)
can you help me?
Edit:
library(shiny)
ui <- fluidPage(
fluidRow(
column(6, offset =3,
wellPanel(
"Choose Mandate and Date",
fluidRow(
column(4,selectInput("pfID",label = "",
choices = list("please select a PF","GF25",
"FPM"),
selected = "please select a PF") ),
column(4, dateInput("pfDate",label="",value = Sys.Date()) ),
column(2, actionButton("go","Submit")),column(2,textOutput("selected_var"))
)
)
)
)
)
# Define server logic ----
server <- function(input, output) {
pfDataReactive <- reactive({
input$go
if (pf_name()!="please select a PF") {
pfData <- read.csv(file =paste(pf_name(),".csv",sep=""),sep=";",dec=",")
MDur <- pfData[1,15]
pfData <- pfData[3:nrow(pfData),]
Total = sum(pfData$Eco.Exp...Value.long)
Assets = sum(as.numeric(gsub(",",".",gsub(".","",pfData$Value,fixed=TRUE),fixed=TRUE)))
pfData$Exposure <- with(pfData, Eco.Exp...Value.long /Total)
pfData
output$selected_var <- renderText({paste(MDur)})
}
})
}
# Run the app ----
shinyApp(ui = ui, server = server)
Thank you
Stefan
Without a working example, it's imposible to be sure what you're trying to do, but it sounds like you need a reactive rather than using observeEvent.
Try something like
pfDataReactive <- reactive({
input$go
pfData <- read.csv(file =paste(pf_name(),".csv",sep=""),sep=";",dec=",")
Total = sum(pfData$Eco.Exp...Value.long)
Assets = sum(as.numeric(gsub(",",".",gsub(".","",pfData$Value,fixed=TRUE),fixed=TRUE)))
pfData$Exposure <- with(pfData, Eco.Exp...Value.long /Total)
pfData
})
And then use pfDataReactive() in your Shiny app's server function wherever you would refer to pfData in your console code.
The standalone reference to input$go ensures the reactive will update whenever input$go changes/is clicked/etc.
Update
There are still significant issues with your code. You've added an assignment to an output object as the last line of the reactive I gave you, so the reactive always returns NULL. That's not helpful and is one of the reasons why it "doesn't active at all"...
Second, you test for the existence of an reactive/function called pf_name when the relevant input object appears to be input$pfID. That's another reason why the reactive is never updated.
Note the change to the definition of input$pfID that I've made to improve the readability of the pfDataReactive object. (This change also probably means that you can do away with input$go entirely.)
As you say, I don't have access to your csv file, so I can't test your code completely. I've modified the body of the pfDataReactive to simply return the mtcars dataset as a string. I've also edited the code I've commented out to hopefully run correctly when you use it with the real csv file.
This code appears to give the behaviour you want,. Though, if I may make a subjective comment, I think the layout of your GUI is appaling. ;=)
library(shiny)
ui <- fluidPage(
fluidRow(
column(6, offset =3,
wellPanel(
"Choose Mandate and Date",
fluidRow(
column(4,selectInput("pfID",label = "",
# Modified to that "Pleaseselect a PF" returns NULL
choices = list("please select a PF"="","GF25", "FPM"),
selected = "please select a PF") ),
column(4, dateInput("pfDate",label="",value = Sys.Date()) ),
column(2, actionButton("go","Submit")),column(2,textOutput("selected_var"))
)
)
)
)
)
# Define server logic ----
server <- function(input, output) {
pfDataReactive <- reactive({
# Don't do anything until we have a PF csv file
req(input$pfID)
input$go
# Note the change to the creation of the file name
# pfData <- read.csv(file =paste(input$pfID,".csv",sep=""),sep=";",dec=",")
# pfData <- pfData[3:nrow(pfData),]
# Total = sum(pfData$Eco.Exp...Value.long)
# Assets = sum(as.numeric(gsub(",",".",gsub(".","",pfData$Value,fixed=TRUE),fixed=TRUE)))
# pfData$Exposure <- with(pfData, Eco.Exp...Value.long /Total)
# MDur <- pfData[1,15]
# If you want to print MDur in the selected_var output, MDur should be the retrun value from this reactive
# MDur
mtcars
})
output$selected_var <- renderText({
print("Yep!")
as.character(pfDataReactive())
})
}
# Run the app ----
shinyApp(ui = ui, server = server)
Next time, please, please, make more effort to provide a MWE. This post may help.
This is a good introduction to Shiny.
I have an R shiny app that gets a .csv import from a user and searches the imported data across a built-in data frame, then gives the % match in the output. The UI is very simple, with a few different inputs (import .csv, a slider, and some radio buttons). What I want is to be able to take the reactive table output and print this to a .csv that the user can download to their machine. The server side of the app looks something like this:
server <- function(input, output){
rvals <- reactiveValues()
observeEvent(input$file_1,{
req(input$file_1)
rvals$csv <<- read.csv(input$file_1$datapath, header = TRUE)
#some data processing here
})
output$contents <- renderTable({
if(input$select == 1){
x <- function
}else if(input$select == 2){
x <- function
}else if(input$select == 3){x <- function}
#some more data processing and formatting here
return(x)
},digits = 4)
}
I would like to have the data table x be able to become a .csv that can be downloaded by clicking a download button. In the server, I added the following code, but when I try to download the data it just downloads a blank file and says "SERVER ERROR" in my downloads manager on my machine.
output$downloadData <- downloadHandler(
filename = "thename.csv",
content = function(file){
write.csv(x, file)
}
In the console I also get the error message:
Warning: Error in is.data.frame: object 'x' not found [No stack trace available]
The object you create inside the expression of renderTable is not available outside of it. Instead you could assign it to the reactive values you set up. Below is a working example (note that I have tried to replicate your code so the data will not be available until you click on "Upload CSV", which here just calls mtcars).
library(shiny)
ui = fluidPage(
sidebarPanel(
actionButton(inputId = "uploadCsv", label = "Upload CSV:", icon = icon("upload")),
selectInput(inputId = "preProc", label = "Pre-processing", choices = c("Mean"=1,"Sum"=2)),
downloadButton("downloadData", label = "Download table")
),
mainPanel(
h4("My table:"),
tableOutput("contents")
)
)
server <- function(input, output) {
rvals <- reactiveValues(
csv=NULL,
x=NULL
)
observeEvent(input$uploadCsv,{
rvals$csv <- mtcars # using example data since I don't have your .csv
# rvals$csv <- read.csv(input$file_1$datapath, header = TRUE)
#some data processing here
})
output$contents <- renderTable({
# Assuing the below are functions applied to your data
req(
input$preProc,
!is.null(rvals$csv)
)
if(input$preProc == 1){
rvals$x <- data.frame(t(colMeans(mtcars)))
}else {
rvals$x <- data.frame(t(colSums(mtcars)))
}
return(rvals$x)
},digits = 4)
output$downloadData <- downloadHandler(
filename = "myFile.csv",
content = function(file){
write.csv(rvals$x, file)
}
)
}
shinyApp(ui,server)
EventReactive already outputs a reactive value, you don't need to create an extra reactiveVal, see example below :
library(shiny)
# Define UI
ui <- fluidPage(
# Application title
titlePanel("Test"),
mainPanel(
actionButton("show", "Download"),
textOutput("result")
)
)
server <- function(input, output) {
csvfile <- eventReactive(req(input$show), ignoreNULL = T, {
"Content of file"
})
output$result <- reactive(
paste("result : ",csvfile()))
}
# Run the application
shinyApp(ui = ui, server = server)
I would also avoid to use <<-operator in a reactive expression.
I have a shiny app which takes a csv file as input and after clicking 'submit' should display a jsoneditOutput. Besides this I have used a reset button which when clicked should reset the file input. But when I click submit I get: Error in read.table: 'file' must be a character string or connection.
library(shiny)
library(shinyjs)
library(tidyverse)
library(listviewer)
library(jsonlite)
library(SACCR)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
useShinyjs(),
fileInput('inFile', 'Choose 1st file'),
actionButton('submit', 'Submit'),
tags$hr(),
actionButton('reset', 'Reset')
),
mainPanel(
jsoneditOutput("choose")
)
)
)
server <- function(input, output, session) {
rv <- reactiveValues(
data = NULL,
clear = FALSE
)
########1st
observe({
req(input$inFile)
req(!rv$clear)
rv$data <- read.csv(input$inFile$datapath,header = T)
})
observeEvent(input$inFile, {
rv$clear <- FALSE
}, priority = 1000)
observeEvent(input$reset, {
rv$data <- NULL
rv$clear <- TRUE
reset('inFile')
}, priority = 1000)
output$choose <- renderJsonedit({input$submit
jsonedit(jsonlite::fromJSON(SACCR::SACCRCalculator(isolate(rv$data), JSON=TRUE)))
})
}
shinyApp(ui, server)
So the issue is with this line:
jsonedit(jsonlite::fromJSON(SACCR::SACCRCalculator(isolate(rv$data), JSON=TRUE)))
The SACCRCalculator function needs a .csv file, not an R dataframe. Try replacing rv$data with input$inFile$datapath.
Also, the SACCRCalculator function requires three files in total; the trades, CSA, and collaterals. So that line will need to be expanded to include all three files. It should end up looking something like:
SACCRCalculator(input$trades$datapath, input$csa$datapath, input$collaterals$datapath, JSON=TRUE)
I understand that reactive values notifies any reactive functions that depend on that value as per the description here
based on this I wanted to make use of this property and create a for loop that assigns different values to my reactive values object, and in turn I am expecting another reactive function to re-execute itself as the reactive values are changing inside the for loop. Below is a simplified example of what i am trying to do:
This is the ui.R
library(shiny)
# Define UI
shinyUI(pageWithSidebar(
titlePanel("" ,"For loop with reactive values"),
# Application title
headerPanel(h5(textOutput("Dummy Example"))),
sidebarLayout(
#Sidebar
sidebarPanel(
textInput("URLtext", "Enter csv of urls", value = "", width = NULL, placeholder = "Input csv here"),
br()
),
# Main Panel
mainPanel(
h3(textOutput("caption"))
)
)
))
This is the server file:
library(shiny)
shinyServer(function(input, output) {
values = reactiveValues(a = character())
reactive({
url_df = read.table(input$URLtext)
for (i in 1:5){
values$a = as.character(url_df[i,1])
Sys.sleep(1)
}
})
output$caption <- renderText(values$a)
})
This does not give the expected result. Actually when I checked the content of values$a
it was null. Please help!
Rather than using a for loop, try using invalidateLater() with a step counter. Here's a working example that runs for me with an example csv found with a quick google search (first column is row index 1-100).
library(shiny)
# OP's ui code
ui <- pageWithSidebar(
titlePanel("" ,"For loop with reactive values"),
headerPanel(h5(textOutput("Dummy Example"))),
sidebarLayout(
sidebarPanel(
textInput("URLtext", "Enter csv of urls", value = "", width = NULL, placeholder = "Input csv here"),
br()
),
mainPanel(
h3(textOutput("caption"))
)
)
)
server <- function(input, output, session) {
# Index to count to count through rows
values = reactiveValues(idx = 0)
# Create a reactive data_frame to read in data from URL
url_df <- reactive({
url_df <- read.csv(input$URLtext)
})
# Reset counter (and url_df above) if the URL changes
observeEvent(input$URLtext, {values$idx = 0})
# Render output
output$caption <- renderText({
# If we have an input$URLtext
if (nchar(req(input$URLtext)) > 5) {
# Issue invalidation command and step values$idx
if (isolate(values$idx < nrow(url_df()))) {
invalidateLater(0, session)
isolate(values$idx <- values$idx + 1)
}
}
# Sleep 0.5-s, so OP can see what this is doing
Sys.sleep(0.5)
# Return row values$idx of column 1 of url_df
as.character(url_df()[values$idx, 1])
})
}
shinyApp(ui = ui, server = server)