Using read.xlsx in Shiny R App - r

I am trying to load an excel file and display the summary. The file is loading without any errors but not displaying anything.
Here is my code
ui.R
library(shiny)
shinyUI(pageWithSidebar(
headerPanel("Analysis"),
sidebarPanel(wellPanel(fileInput('file1', 'Choose XLSX File',
accept=c('sheetName', 'header'), multiple=FALSE))),
mainPanel(
tabsetPanel(
tabPanel("Tab1",h4("Summary"), htmlOutput("summary"))
)))
server.R
library(shiny)
shinyServer(function(input, output) {
dataset = reactive({
infile = input$file1
if (is.null(infile))
return(NULL)
infile_read = read.xlsx(infile$datapath, 1)
return(infile_read)
})
output$summary <- renderPrint({
summary = summary(dataset())
return(summary)
})
outputOptions(output, "summary", suspendWhenHidden = FALSE)
})

I haven't tested this, but it looks like you're not actually returning anything from dataset(). Change the function to:
dataset = reactive({
infile = input$file1
if (is.null(infile))
return(NULL)
read.xlsx(infile$datapath, 1)
})
When you do infile_read = read.xlsx(infile$datapath, 1), you're reading the file into infile_read but then you're not actually returning it. Reactives work just look any R function really. Try running this:
f <- function() x <- 10
f()
You should see that f() doesn't return anything. All it's doing is making an assignment that goes nowhere. To actually return 'hello' you would do:
f <- function() {
x <- 'hello'
x
}
Or just:
f <- function() 'hello'

Related

Downloading the outputs of a reactive table in R 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.

R Shiny: Perform a series of functions on reactive input

I want to perform a series of tasks on a data.frame that will be loaded by the user via actionButton. Here is an example where I want to remove rows with NAs in the third column of the data.frame selected by the user. I get the error:
"Warning: Error in observeEventHandler: object 'df' not found
Stack trace (innermost first):
65: observeEventHandler [(file location).R#56]"
Why doesn't observeEvent recognize the variable f?
Server.R
library(shiny)
shinyServer <- function(input, output) {
filedata <- reactive({
infile <- input$Samples
if (is.null(infile)) {
# User has not uploaded a file yet
return(NULL)
}
df <- read.table(infile$datapath,sep="\t",skip =0, header = TRUE,na.strings = "NA",stringsAsFactors=FALSE)
})
observeEvent(input$Click, {
selectA <- df[complete.cases(f[,3]),]
}
}
ui.R
library(shiny)
shinyUI( <- fluidPage(
tabPanel("Inputs",
wellPanel(fileInput(inputId = "Samples", label = "Import File"),
actionButton(inputId = "Click", label = "Samples")),
h2('Results'),
dataTableOutput("Results")))
Maybe I didn't do a good job of articulating my question. Here is the answer that I was looking for.
Server.R
library(shiny)
shinyServer <- function(input, output) {
filedata <- reactive({
infile <- input$Samples
if (is.null(infile)) {
# User has not uploaded a file yet
return(NULL)
}
read.table(infile$datapath,sep="\t",skip =0, header = TRUE,na.strings = "NA",stringsAsFactors=FALSE)
})
observeEvent(input$Click, {
df <- filedata()
selectA <- df[complete.cases(df[,3]),]
}
}

DownloadHandler function in R package shiny does not produce a csv file for downloading

In my below example of a simple shiny app i recently created, im currently trying to include also the possibility of downloading a data frame that is created from the results. I mention here part of the server.R script in order to not make a huge post:
shinyServer(function(input, output) {
table_options<- list(lengthMenu = list(c(5,10,15,20),
c('5','10', '15', '20')), pageLength = 15, ordering=TRUE,
class = 'cell-border stripe',dom ='t',scrollX = TRUE,
fixedColumns = list(leftColumns = 2, rightColumns = 1))
inTable <- reactive({# upload a tsv file
inFile <- input$file1
if (is.null(inFile))
return(NULL)
read.table(inFile$datapath,header=input$header,
sep="\t",stringsAsFactors = FALSE)
}) #END REACTIVE
rv <- reactiveValues()
rv$data <- NULL # to further use it into the observeEvent below
observeEvent(input$goButton, {
df <- inTable()
# some data manipulation with df...
if(input$repo_option=="mimic"){
# some functions here that result to a data frame named final dat
rv$data <- final.dat
rv$data
}
else if(input$repo_option=="reverse"){
# similar procedure...
rv$data <- final.dat
rv$data
}
})
output$contents <- DT::renderDataTable({
expr=DT::datatable(rv$data, options=table_options,
extensions ='FixedColumns',selection="none")
})
output$downloadData <- downloadHandler(
filename = function() { paste("input$file1", ".csv", sep=",") },
content = function(file) {
write.csv(rv$data,file)
}
)
})
My main issue is that, although the output$contents works fine in the app, when i press the download button from the ui.R server (not posted here for simplicity), the download "pop-up" window appears, but the saving does not work. Thus, i suspect that is something wrong with the code in the downloadHandler function, but any ideas or help ?

shiny fileinput r dataframe

Using R shiny, I am developing a simple app that allows user to input data from a file. With csv or txt files everything works fine, but I can not make R dataframes to load.
## SERVER.R
shinyServer(function(input, output) {
infile <- reactive({
infile <- input$datafile
if (is.null(infile)) {
# User has not uploaded a file yet
return(NULL)
}
infile<load(input$datafile$datapath)
})
myData <- reactive({
df<-infile()
if (is.null(df)) return(NULL)
})
output$value1 <- renderPrint({
names(iris)
})
output$value2 <- renderPrint({
names(myData())
})
load("iris.Rdata") ## data loaded for testing
})
## UI.R
shinyUI(fluidPage(
fileInput("datafile", label = h3("File input")),
fluidRow(column(4, verbatimTextOutput("value1"))),
fluidRow(column(4, verbatimTextOutput("value2")))
))
When I run this app I can see the names of the iris dataset loaded only for testing, but respect the names of the loaded file (which should be rendered as value2) only shows "NULL"
Any help?? thanks in advance!
I think this is what you want. You had a couple of typos, and you probably didn't quite understand what load actually does, it loads a set of objects into memory.
I did the following things:
added some initialization code to save a couple of .Rdata for testing, they both have exactly one object in them, a dataframe. The code needs this.
add a line to parse out the first object in that loaded datafile and return it
Here is the code:
server.r
## SERVER.R
#Initialization
library(datasets)
save(iris,file="iris.Rdata")
save(mtcars,file="m.Rdata")
shinyServer(function(input, output) {
infile <- reactive({
infile <- input$datafile
if (is.null(infile)) {
# User has not uploaded a file yet
return(NULL)
}
objectsLoaded <- load(input$datafile$name)
# the above returns a char vector with names of objects loaded
df <- eval(parse(text=objectsLoaded[1]))
# the above finds the first object and returns it
return(df)
})
myData <- reactive({
df<-infile()
if (is.null(df)) return(NULL)
return(df)
})
output$value1 <- renderPrint({
names(iris)
})
output$value2 <- renderPrint({
names(myData())
})
load("iris.Rdata") ## data loaded for testing
})
ui.r
## UI.R
shinyUI(fluidPage(
fileInput("datafile", label = h3("File input")),
fluidRow(column(4, verbatimTextOutput("value1"))),
fluidRow(column(4, verbatimTextOutput("value2")))
))
Here is the output:

Rshiny gives error after loading rpart.object type using .RData file

I have saved the .Rdata file, which contains 3 R objects:
1. Vector
2. Character String
3. rpart.object (I figured out that this object in .RData only creating issue, as if I remove this object from .RData file, Shiny app works fine.)
Whenever I load the .RData file and refresh the application Rshiny gives error below:
Error in .rs.getShinyFunction(params$name, params$where) :
attempt to apply non-function
In order to avoid above issue, I tries following options:
Load the .RData in Global environment.
load(infile$datapath,.GlobalEnv)
Load the .RData in New Environment.
LoadToEnvironment <- function(RData, env = new.env()) { load(RData, env)
return(env) }
e <- LoadToEnvironment("D:\Demo NBA\AddOnPropensity.R")
val_modtyp <- e$val_modtyp
val_model <- e$val_model
val_b <- e$val_b
Load data Using attach()
Code:
require(shinydashboard)||install.packages("shinydashboard"); library(shinydashboard)
require(shiny)||install.packages("shiny"); library(shiny)
require(shinyjs)||install.packages("shinyjs"); library(shinyjs)
ui <- fluidPage(
useShinyjs(),
extendShinyjs(text = "shinyjs.refresh = function() { location.reload(); }"),
fluidPage(id="Q1",useShinyjs(),
dashboardPage(dashboardHeader(title="Test",titleWidth=400),
dashboardSidebar(),
dashboardBody (
tabItem("PMData",
fileInput('filepm', 'Choose Data to Upload',accept = c(".R")),
uiOutput('ui.PM2'),
actionButton("savepm","Save"),
uiOutput("ui.PM3")
)
)
)
))
server <- function(session,input,output){
hide("savepm")
dfPM <<- data.frame(Category=character(),
PredictiveModel=character(),
OfferIdentifier=character(),
stringsAsFactors=FALSE)
LoadToEnvironment <<- function(RData, env = new.env())
{
load(RData, env)
return(env) }
val_choices <- reactive({
if (is.null(input$filepm)){
return()
}
infile <- input$filepm
e <- LoadToEnvironment(infile$datapath)
e$val_b
})
observeEvent(input$filepm,{
useShinyjs()
if (is.null(input$filepm)){
return()
}
output$ui.PM2 <- renderUI ({
selectInput("offered",label= "Offered Test",choices = val_choices(),
selected = NULL)
})
show("ui.PM2")
show("savepm")
})
val_pmfile <- reactive({
if (is.null(input$filepm)){
return()
}
infile <- input$filepm
infile$datapath
})
TempPredmodDF <- reactive({
if(is.null(input$offered))
{
return()
}else{
data.frame(Category="Test",
PredictiveModel=val_pmfile(),
OfferIdentifier=input$offered,
stringsAsFactors=FALSE)}
})
observeEvent(input$savepm,
{
useShinyjs()
tempPMdf <- TempPredmodDF()
if(nrow(dfPM[dfPM$Category==tempPMdf$Category,]) == 0)
{
dfPM <<- rbind(dfPM,tempPMdf)
}else
{
getidx <- as.numeric(which( dfPM[,1] == tempPMdf$Category ))
dfPM[getidx,2] <<- tempPMdf$PredictiveModel
dfPM[getidx,3] <<- tempPMdf$OfferIdentifier
}
output$ui.PM3 <- renderTable({
dfPM},include.rownames=FALSE)
hide("ui.PM2")
hide("savepm")
show("ui.PM3")
})
}
app <- shinyApp(ui,server)
runApp(app,port = 7000,launch.browser = getOption("shiny.launch.browser", interactive()))

Resources