shiny fileinput r dataframe - r

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:

Related

Why does this Shiny App not display dataframe using RStudio?

I have a list of data frames, ls_df, comprising two dataframes from the datasets package.
I am trying to load these two dataframes into a Shiny app using the code below. However, it does not work, with the error message no item called "ls_df" on the search list being returned. Does anyone know how to fix?
ls_df <- list(datasets::airmiles,
datasets::AirPassengers)
ui <- fluidPage(
selectInput("ls_df", label = "Dataset", choices = ls("ls_df")),
verbatimTextOutput("summary"),
tableOutput("table")
)
server <- function(input, output, session) {
output$summary <- renderPrint({
dataset <- get(input$ls_df, "ls_df")
summary(dataset)
})
output$table <- renderTable({
dataset <- get(input$ls_df, "ls_df")
dataset
})
}
shinyApp(ui, server)
The list needs the names:
library(shiny)
ls_df <- list(airmiles=datasets::airmiles,AirPassengers=datasets::AirPassengers)
ui <- fluidPage(
selectInput("ls_df", label = "Dataset", choices = names(ls_df)),
verbatimTextOutput("summary"),
tableOutput("table")
)
server <- function(input, output, session) {
output$summary <- renderPrint({
dataset <- ls_df[[input$ls_df]]
summary(dataset)
})
output$table <- renderTable({
dataset <- ls_df[[input$ls_df]]
dataset
})
}
shinyApp(ui, server)
Two things wrong:
Your list needs names, as discussed in PorkChop's answer. If this were the only required change, then PorkChop's answer would suffice.
get(input$ls_df, "ls_df") is an error. This should be rather clear, though, since it prevents the shiny interface from starting. This error is because the envir= argument of ls and get require an object, not the character name of an object. (One could go "inception" and use ls(get("ls_df")) and similarly for get, but that hardly seems necessary or useful.)
ls_df <- list(airmiles=datasets::airmiles, # <-- named list
AirPassengers=datasets::AirPassengers)
ui <- fluidPage(
selectInput("ls_df", label = "Dataset", choices = ls(ls_df)), # <-- no quotes
verbatimTextOutput("summary"),
tableOutput("table")
)
server <- function(input, output, session) {
output$summary <- renderPrint({
dataset <- get(input$ls_df, ls_df) # <-- no quotes
summary(dataset)
})
output$table <- renderTable({
dataset <- get(input$ls_df, ls_df) # <-- no quotes
dataset
})
}

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)

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]),]
}
}

Cannot populate drop down menu dynamically in R shiny

I am trying to create an APP using R Shiny. I want to upload data (.csv file). Then I want to populate the column names in CSV file in a drop down menu. I am unable to do that.
Please refer to the codes below :
---- server.r -----
library(shiny)
options(shiny.maxRequestSize = 32*1024^2)
shinyServer(
function(input, output){
data <- reactive({
file1 <- input$file
if(is.null(file1)){return()}
read.table(file=file1$datapath,head=TRUE,sep=",")
})
output$sum <- renderTable({
if(is.null(data())){return ()}
summary(data())
})
output$table <- renderTable({
if(is.null(data())){return ()}
data()
})
# the following renderUI is used to dynamically generate the tabsets when the file is loaded. Until the file is loaded, app will not show the tabset.
output$tb <- renderUI({
if(is.null(data()))
h5("no file loaded")
else
tabsetPanel(tabPanel("Data", tableOutput("table")),tabPanel("Summary", tableOutput("sum")))
})
output$col <- renderUI({
selectInput("phenomena", "Select the Phenomena", names(data))
})
})
----- ui.R -----
library(shiny)
shinyUI(fluidPage(
titlePanel("Hotspot Analysis of EnviroCar Data"),
sidebarLayout(
sidebarPanel(
# uploading the file
fileInput("file","Upload *.csv file"), # fileinput() function is used to get the file upload contorl option
uiOutput("col")
),
mainPanel( uiOutput("tb") )
)
))
I guess the problem is in server.R:
selectInput("phenomena", "Select the Phenomena", names(data))
Here, you're using data without parentheses so what you actually obtain is the source code of the function data, and names(data) is NULL. I think all you need is to replace names(data) by names(data()).

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