Object Not found error in my Shiny server.R code - r

I am new to R programming. When I execute my shiny app code, I get the error "Error in func() : object 'file3' not found". Any suggestions on how to resolve this? Below is the server.R code where I have the error:
library(shiny)
shinyServer(function(input, output) {
reactive ({
if(is.null(input$file1)) return(NULL)
fl1 <- paste("file:///",input$file1,sep='')
if(is.null(input$file2)) return(NULL)
fl2 <- paste("file:///",input$file2,sep='')
file1 <- read.table(fl1,sep=',',header=TRUE)
file2 <- read.table(fl2,sep=',',header=TRUE)
library(sqldf)
options(gsubfn.engine = "R")
file3 <- sqldf('SELECT * FROM file2 UNION ALL SELECT * FROM file1')
})
output$text1 <- renderTable({ file3 })
})

I am answering based on the code provided, since you reference input$xx, I assume that you have a ui.R file :-). Also if your files are uploaded files you will need to handle them using shiny::observeEvent, otherwise input$file1 and input$file2 will always be NULL.
You also should ensure that the UI object with inputID = "text1" is defined as a dataTable output rather than a textOutput. So something like this: shiny::dataTableOutput("text1"). This will ensure that your input is parsed correctly.
I have also fixed some of your styling to make you code more readable. See google R Style Guide.
You can try the following, taking into account the above:
library(shiny)
library(sqldf)
options(gsubfn.engine = "R")
shinyServer(function(input, output) {
getData <- reactive ({
if(is.null(input$file1)) return(NULL)
fl1 <- paste("file:///", input$file1, sep = '')
if(is.null(input$file2)) return(NULL)
fl2 <- paste("file:///", input$file2, sep='')
file1 <- read.table(fl1, sep = ',', header = TRUE)
file2 <- read.table(fl2, sep = ',', header = TRUE)
file3 <- sqldf('SELECT * FROM file2 UNION ALL SELECT * FROM file1')
return(file3)
})
output$text1 <- shiny::renderDataTable({ getData() })
})
I hope this helps. You may also want to try using DT::renderDataTable instead of shiny::renderDataTable

Related

Rename Colnames from dataframe

I am making a Shiny App and I would like to rename the first variable from dataframe, to make after a corrplot.
In normal R the code is:
library(lares)
names(Dataset)[1] <- "DR"
corr_var(Dataset, DR, top=20)
And in Shiny I have something:
dataReg2 = reactive({
inFile <- input$fileReg
if (is.null(inFile))
return(NULL)
else
data1 = read_excel(inFile$datapath)
return(data1)
})
plot=reactive({
names(dataReg2())[[1]]='DR'
corr_var(dataReg2(), DR , top = 20 )
})
But it doesn't work, the error is invalid (NULL) left side of assignment...
Thank you in advance.
You cannot change the column names of reactive object. Copy the data in another variable and you can change the column name of that variable. See this simple example using mtcars.
library(shiny)
ui <- fluidPage(
tableOutput('tab')
)
server <- function(input, output) {
data <- reactive(mtcars)
output$tab <- renderTable({
new_table <- data()
names(new_table)[1] <- 'new'
head(new_table)
})
}
shinyApp(ui, server)

Solved: How do I properly utilise reactive expressions to get this plot to work in RShiny?

Problem
Hi, very new to RShiny (though not R) and I'm trying to write a simple application that at the moment takes 3 CSVs (will likely make this an xlsx with multiple sheets), performs a function called maic (omitted for brevity) on the first 2 which essentially adds in an extra column called 'wt', then binds a subset of that joined data frame to the third CSV. I then call survfit() from the survival library on the joined data and try to plot it but I get this appearing in the app window:
Error: could not find function "joinedData"
My code is below, it seems that survfit() just doesn't recognise that joinedData() exists even though I can render joinedData() in the app window so clearly it does. I'm sure it must be because of how I've defined the reactive expressions but I can't for the life of me figure out why this doesn't work. Any help very gratefully received!
Code (now edited to the solution)
ui <- fluidPage(
fileInput("ipdFile", NULL, accept = c(".csv", ".tsv")),
fileInput("agdFile", NULL, accept = c(".csv", ".tsv")),
fileInput("compdFile", NULL, accept = c(".csv", ".tsv")),
tableOutput("ipd"),
tableOutput("agd"),
tableOutput("compd"),
textOutput("key"),
tableOutput("weightsd"),
plotOutput("kmcurve")
)
server <- function(input, output, session) {
ipdData <- reactive({
req(input$ipdFile)
ext <- tools::file_ext(input$ipdFile$name)
switch(ext,
csv = vroom::vroom(input$ipdFile$datapath, delim = ","),
tsv = vroom::vroom(input$ipdFile$datapath, delim = "\t"),
validate("Invalid file; Please upload a .csv or .tsv file")
)
})
agData <- reactive({
req(input$agdFile)
ext <- tools::file_ext(input$agdFile$name)
switch(ext,
csv = vroom::vroom(input$agdFile$datapath, delim = ","),
tsv = vroom::vroom(input$agdFile$datapath, delim = "\t"),
validate("Invalid file; Please upload a .csv or .tsv file")
)
})
compData <- reactive({
req(input$compdFile)
ext <- tools::file_ext(input$agdFile$name)
switch(ext,
csv = vroom::vroom(input$compdFile$datapath, delim = ","),
tsv = vroom::vroom(input$compdFile$datapath, delim = "\t"),
validate("Invalid file; Please upload a .csv or .tsv file")
)
})
# Reactive expressions
weightsData <- reactive({
req(ipdData())
req(agData())
maic(
ipd=ipdData(),
agd=agData()
)
})
joinedData <- reactive({
req(weightsData())
req(compData())
weightsData() %>% select('TRT',
'AVAL',
'CNSR',
'wt'
) %>%
bind_rows(compData() %>% mutate(wt=1))
})
kmCurve <- reactive({
req(joinedData())
survfit(
Surv(AVAL, CNSR)~TRT,
weights=wt,
data=joinedData()
)
})
# Outputs rendered to UI
output$ipd <- renderTable({
head(ipdData())
})
output$agd <- renderTable({
head(agData())
})
output$weightsd <- renderTable({
joinedData()
})
output$kmcurve <- renderPlot({
ggsurvplot(kmCurve(),
data <- joinedData(),
combine=TRUE,
title="Weighted KM curve",
risk.table=TRUE,
legend="none",
palette="lancet",
xlim=c(0,25),
break.time.by=1
)
})
}
shinyApp(ui, server)

"Shiny App" Uploads file -> Does Something -> Outputs file

I am trying to write my first Shiny App that reads a PDF file, extracts tables and saves it into Excel document.
I am failing to produce suitable code. So far I have:
1) For UI
shinyUI(fluidPage(
titlePanel("CMM Report"),
sidebarPanel(
fileInput("file", "Upload Report")
),
downloadButton("dl", "Download")
))
2) For Server
library(shiny)
library (tabulizer)
library(writexl)
shinyServer(function(input, output) {
data <- reactive({
file1 <- input$file
if(is.null(file1)){return()}
file1 <- ExtractTable (file1)
})
## Download
output$dl <- downloadHandler(
filename = function() { "ae.xlsx"},
content = function(file) {write_xlsx(data, path = file)}
)
})
I am not sure If I need to put the code for extracting table in a function and where to call the function, to make it work. Any help REALLY appreciated.
The data file of the example is from here
report <- "http://www.stat.ufl.edu/~athienit/Tables/Ztable.pdf"
Function to extract data
ExtractTable <- function (report){
lst <- extract_tables(report, encoding="UTF-8")
# Delete blank columns
lst[[1]] <- lst[[1]][, -3]
lst[[2]] <- lst[[2]][, -4]
# Bind the list elements
table <- do.call(rbind, lst)
table <- as.data.frame(table[c(2:37, 40:nrow(table)), ],
stringsAsFactors=FALSE) # ...w/o obsolete rows
# Take over colnames, cache rownames to vector
colnames(table) <- table[1, ]
rn <- table[2:71, 1]
table <- table[-1,-1] # and bounce them out of the table
# Coerce to numeric
table <- as.data.frame(apply(table[1:70,1:10], 2,
function(x) as.numeric(as.character(x))))
rownames(table) <- rn
return(table)
}
Could you try:
shinyServer(function(input, output) {
data <- reactive({
file1 <- input$file
if(is.null(file1)){return()}
ExtractTable(file1$datapath) # $datapath was missing
})
## Download
output$dl <- downloadHandler(
filename = function() { "ae.xlsx"},
content = function(file) {write_xlsx(data(), path = file)} # parentheses () were missing
)
})

Reactive Loading in R Shiny [duplicate]

I want to import a .RData file with fileInput but It doesn't work, I have this error message :
Error in my.data$TYPE_DE_TERMINAL : $ operator is invalid for
atomic vectors
dt <- reactive({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
load(inFile$datapath)
})
GetData <- reactive({
my.data <- dt()
When I try my application with a .RData imported manually it works well (I remplaced dt() directly with a dataframe in my directory) ...
The following example solves the problem. It allows you to upload all .RData files.
Thanks to #Spacedman for pointing me to a better approach of loading the data:
Load the file into a new environment and get it from there.
For the matter of the example being "standalone" I inserted the top section that stores two vectors to your disk in order to load and plot them later.
library(shiny)
# Define two datasets and store them to disk
x <- rnorm(100)
save(x, file = "x.RData")
rm(x)
y <- rnorm(100, mean = 2)
save(y, file = "y.RData")
rm(y)
# Define UI
ui <- shinyUI(fluidPage(
titlePanel(".RData File Upload Test"),
mainPanel(
fileInput("file", label = ""),
actionButton(inputId="plot","Plot"),
plotOutput("hist"))
)
)
# Define server logic
server <- shinyServer(function(input, output) {
observeEvent(input$plot,{
if ( is.null(input$file)) return(NULL)
inFile <- isolate({input$file })
file <- inFile$datapath
# load the file into new environment and get it from there
e = new.env()
name <- load(file, envir = e)
data <- e[[name]]
# Plot the data
output$hist <- renderPlot({
hist(data)
})
})
})
# Run the application
shinyApp(ui = ui, server = server)

Using read.xlsx in Shiny R App

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'

Resources