I want to sub set my data based on the columns selected dynamically by check-box input. Is there any way in which I can make my input file globally available in my code so that further operations can be easily performed.
Following is my code:
Server.R
library(shiny)
shinyServer(function(input, output) {
dInput <- reactive({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
finput <- read.csv(inFile$datapath, header=TRUE, sep=',',quote="'")
fheaders <- names(finput)
return(fheaders)
})
output$choose_columns <- renderUI({
checkboxGroupInput("columns", "Choose columns",
choices = dInput(),
selected = NULL)
})
# to observe in environment which columns are selected
observe({ print(input$columns) })
output$data_table <- renderTable({
# If missing input, return to avoid error later in function
if(is.null(input$file1))
return()
# Get the data set
dat <- get(input$file1)
# Keep the selected columns
dat <- dat[, input$columns, drop = FALSE]
# Return first 20 rows
head(dat, 20)
})
})
ui.R
library(shiny)
# Define UI for application
shinyUI(fluidPage(
# Application title
titlePanel("Subset a table"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
uiOutput("choose_columns")
),
mainPanel(
tableOutput("data_table")
)
)
))
I'm getting following error while displaying tableOutput("data_table")
Error : invalid first argument
I think you need a reactive
on your dInput
and added one more on your filtered data. You can then use data_table()
(with the ()
) for further operations. The (single file) code below works fine on my machine. I also remove the observe
(useless) and changed what dInput
returns (the actual file rather than colnames).
library(shiny)
server <- shinyServer(function(input, output) {
dInput <- reactive({
inFile <- input$file1
if (is.null(inFile))
return(NULL)
else
return(read.csv(inFile$datapath, header=TRUE, sep=',',quote="'"))
})
output$choose_columns <- renderUI({
cn <- colnames(dInput())
selectInput("columns", "Choose columns",
choices = cn,
selected = cn,
size=10,
multiple=TRUE, selectize=FALSE)
})
data_table <- reactive({
# If missing input, return to avoid error later in function
if(is.null(input$file1))
return(NULL)
# Get the data set
dat <- dInput()
# Keep the selected columns
dat[, input$columns, drop = FALSE]
})
output$data_table <- renderTable(data_table())
})
# Define UI for application
ui <- shinyUI(fluidPage(
# Application title
titlePanel("Subset a table"),
sidebarLayout(
sidebarPanel(
fileInput('file1', 'Choose CSV File',
accept=c('text/csv',
'text/comma-separated-values,text/plain',
'.csv')),
uiOutput("choose_columns")
),
mainPanel(
h3("Filtered table"),
tableOutput("data_table")
)
)
))
shinyApp(ui, server)
is that what you want?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.