Subseting object with reactive values will fail - r

List item
I have a problem with reactive values not working as i think it should work.
The small code below describes the problem. The function firstsub2 will basically subset an object into a smaller one by removing samples we don´t want to keep for some reason (this is using the subset_samples function from the phyloseq biocondcutor package).
UI.R
myui <-
fluidPage(
navbarPage("Project",
## foldchanges
tabPanel("Foldchanges",
titlePanel("Permanova: Analysis of variance using distance matrices"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
actionButton("dofoldchanges", "Generate foldchanges")
),
mainPanel(
# Output: Tabset w/ plot, summary, and table ----
tabsetPanel(id="foldchanges",type = "tabs",
tabPanel(title="Summary", value=1, verbatimTextOutput("summary_foldchanges"))
#tabPanel("Table pairwise",value=4, dataTableOutput("tablepermanovapw"))
)
)
)
)
)
)
SERVER.R
#To install phyloseq
#source("https://bioconductor.org/biocLite.R")
#biocLite("phyloseq")
library(shiny)
library(phyloseq)
myserver <- function(input, output, session) {
source("foldchanges.R", local = TRUE)
}
foldchanges.R
# Filter object
firstsub2 <- reactive({
values$rn <- as.character(sample_data(values$physeq)[,"Description"]$Description)))
cat(values$rn)
#The subset_samples function below will not work
filteredtaxo <- subset_samples(values$physeq, Description %in% values$rn)
return(filteredtaxo)
})
values <- reactiveValues()
observeEvent(input$dofoldchanges, {
rich_sparse_biom = system.file("extdata", "rich_sparse_otu_table.biom", package = "phyloseq")
physeq = import_biom(rich_sparse_biom, parseFunction = parse_taxonomy_greengenes)
print(physeq)
values$physeq <- physeq
values$filtered <- firstsub2()
})
This example will basically return the same object that was imported

Your code still has some errors, especially the server file (Some unnecessary commas).
I think your app works as it should, but it will always be the same file as the values$rn will always be the same. I included another line (uncommented right now) below your subset_sample, to test if the subsetting is working. If you change values$rn to "human skin" for example, you will see different results.
But I didn't figure out how to change it. When taking only the first element of values$rn for example, I'm getting an object not found error. But when I include "human skin" like that, it works.
But maybe that helps you already.
library(shiny)
# source("https://bioconductor.org/biocLite.R")
# biocLite("phyloseq")
library(phyloseq)
myui <- {fluidPage(
navbarPage("Project",
## foldchanges
tabPanel("Foldchanges",
titlePanel("Permanova: Analysis of variance using distance matrices"),
# Sidebar layout with input and output definitions ----
sidebarLayout(
# Sidebar panel for inputs ----
sidebarPanel(
actionButton("dofoldchanges", "Generate foldchanges")
),
mainPanel(
# Output: Tabset w/ plot, summary, and table ----
tabsetPanel(id="foldchanges",type = "tabs",
tabPanel(title="Summary", value=1,
verbatimTextOutput("summary_foldchanges"),
verbatimTextOutput("summary_physeq"))
)))))
)}
myserver <- function(input, output, session) {
values <- reactiveValues()
firstsub2 <- reactive({
req(values$physeq)
input$dofoldchanges
values$rn <- as.character(sample_data(values$physeq)[,"Description"]$Description)
cat(values$rn)
#The subset_samples function below will not work
filteredtaxo <- subset_samples(values$physeq, "Description" %in% values$rn)
## Change it to one of the next lines, to see that subsetting works.
# filteredtaxo <- subset_samples(values$physeq, Description %in% "human skin")
# filteredtaxo <- subset_samples(values$physeq, Description %in% "human gut")
return(filteredtaxo)
})
observeEvent(input$dofoldchanges, {
rich_sparse_biom = system.file("extdata", "rich_sparse_otu_table.biom", package = "phyloseq")
physeq = import_biom(rich_sparse_biom, parseFunction = parse_taxonomy_greengenes)
print(physeq)
values$physeq <- physeq
values$filtered <- firstsub2()
})
output$summary_physeq <- renderPrint({
req(values$physeq)
values$physeq
})
output$summary_foldchanges <- renderPrint({
req(values$filtered)
values$filtered
})
}
shinyApp(myui, myserver)

Related

Using the lapply() function in a Shiny module to build a tabBox with multiple tabPanel whose amount depends on the imported data

I want to build a module in shiny that renders a tabBox with the number of tabPanel as a function of the data. The simulated data (see script below) has the tank or pond variable (column) ("viveiro" in Portuguese) whose quantity can be a variable. So the number of panels is a function of this variable. But the biggest problem is when inside each tabPanel I render a simple table (with renderTable()) that corresponds to a subset of each "viveiro" (tank/pond). I use the lapply() function both to build the renderUI and to assign the reactive expression to the outputs (see the applicable example below). nCiclo() is a reactive that represent the number of "viveiro" (tank/pond as you prefer) that can correspond to a sequence of 1:6 for example. It works well on the first lapply() in renderUI() for output$tab_box, but it doesn't work when I use it on the second lapply() for the output[[paste0('outCiclo',j)]] outputs in renderTable below.
Question:
How do I put this last lapply() function as a function of the number of "viveiro" (tank/pond) in the simulation data? I tried to replace the fix sequence 1:6 for reactive nCiclo() but does not work.
library(shiny)
library(shinydashboard)
library(openxlsx)
rm(list = ls())
#--------------------------------------------------
# Simulated data for the app
(n = 2*sample(3:8,1)) # tank/pond (portuguese viveiro) number (quantity) / random variable in the data
bio <- data.frame(
semana = rep(1:5,n),
peso = rnorm(5*n,85,15),
viveiro = rep(1:2,each=(5*n)/2),
ciclo = rep(1:n,each=5)
)
# An excel file will be saved to your Working Directory
# Use the file to import into the app
write.xlsx(bio,'bio.xlsx')
#--------------------------------------------------
####### Module #######
# UI Module
dashMenuUI <- function(id){
ns <- NS(id)
uiOutput(ns("tab_box"))
}
# Server Module
dashMenuServer <- function(id,df){
moduleServer(id,function(input,output,session){
ns <- session$ns
nCiclo <- reactive(unique(df()$ciclo)) # nCycle is simply 1:6 sequence.
output$tab_box <- renderUI({
do.call(tabBox, c(id='tabCiclo',
lapply(nCiclo(), function(i) {
tabPanel(
paste('ciclo', i),
tableOutput(outputId = ns(paste0('outCiclo',i)) )
)
}))
)
})
# The problem is here. I want to put the lapply function as a function of the pond/tank (portuguese viveiro) number (simulated data).
# but the nCycle() reactive doesn't work in place of 1:6
lapply(1:6, function(j) {
output[[paste0('outCiclo',j)]] <- renderTable({
subset(df(), ciclo==j)
})
})
})
}
#------------------------------------------------------
ui <- dashboardPage(
dashboardHeader(title = "Teste Módulo TabBox Dinâmico"),
dashboardSidebar(
sidebarMenu(
menuItem('Ciclo e viveiro',tabName = 'box_din')
)
),
dashboardBody(
tabItems(
tabItem(tabName='box_din',
fileInput(inputId = "upload",label = "Carregue seu arquivo", accept = c(".xlsx")),
dashMenuUI('tabRender')
)
)
)
)
server <- function(input, output, session) {
dados <- reactive({
req(input$upload)
file <- input$upload
ext <- tools::file_ext(file$datapath)
req(file)
validate(need(ext == "xlsx", "Por gentileza insira um arquivo de Excel (extensão .xlsx)"))
df <- read.xlsx(file$datapath,sheet = 1)
df
})
# Ciclo output
dashMenuServer('tabRender',dados)
}
shinyApp(ui, server)
When running the first session of the script note that you get an excel file (.xlsx) in your Working Directory, it is the simulated data to import into the app. The problem is that the 1:6 sequence is fixed and doesn't vary depending on the data (the cycles above 6 are not rendered in the panels), when I replace 1:6 with nCiclo() (try to test for yourself) (it is found in the server module) doesn't work.
I'm not sure if I made myself clear or if the English are understandable, but I thank you for taking the time to read the problem and help in my learning.
Calling nCicle() must be done in a reactive environment, which #Mikael's solution creates using observeEvent() (see comments). Another way is simply to move the lapply(nCiclo(), ...)) up into the output$tab_box <- renderUI() function:
output$tab_box <- renderUI({
lapply(nCiclo(), function(j) {
output[[paste0('outCiclo',j)]] <- renderTable({
subset(df(), ciclo==j)
})
})
do.call(tabBox, c(id='tabCiclo',
lapply(nCiclo(), function(i) {
tabPanel(
paste('ciclo', i),
tableOutput(outputId = ns(paste0('outCiclo', i)) )
)}
))
)
})
Good example of creating dynamic content in a Shiny app.

Dataframe - R - Shiny

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.

To create numericinput for all columns in a data set using renderui

I am trying to create numeric boxes for all column names in a data set. I have written below code but this displays a blank page. Not sure what the error is. Any suggestions?
library(shiny)
library(readr)
shinyApp(
ui <- fluidPage(
uiOutput("TestColumns")
),
server <- function(input, output) {
data_set <- read.csv("Data/170210_Flat_File.csv")
output$TestColumns <- renderUI({
for(i in names(data_set)){
numericInput(i, i,30)
}}
)})
First off, when you ask questions you should ALWAYS post a minimal reproducible example. That is basically something that we can run to replicate the issue you are having so that it is much easier for us to help you. This way we don't have to go about using different data, trying to figure out exactly what your error is. See this link for a good intro: How to make a great R reproducible example?
Next to your question - since you didn't explicitly post an error you were seeing or explicitly state what your issue was I'm going to go ahead and assume that your issue is that you don't see any UI's popping up when you run your Shiny App (this is what I got when I tried running your code with different sample data).
The reason you aren't seeing anything is because you aren't returning any objects from your for loop. If you really wanted to do a for loop you would have to loop through, store everything in a list, then return that list. Note that I had to use R's built in data because you didn't provide any. Something like this would work:
shinyApp(
ui <- fluidPage(
#numericInput("test","test",30),
uiOutput("TestColumns")
),
server <- function(input, output) {
data_set <- mtcars
output$TestColumns <- renderUI({
L<-vector("list",length(names(data_set)))
for(i in names(data_set)){
L[[i]]<-numericInput(i, i,30)
}
return(L)
})})
This should give you your desired result. However, the above is unnecessarily complicated. I suggest you use an lapply instead. Something like this is much better in my opinion:
shinyApp(
ui <- fluidPage(
#numericInput("test","test",30),
uiOutput("TestColumns")
),
server <- function(input, output) {
data_set <- mtcars
output$TestColumns <- renderUI({
lapply(names(data_set),function(x){numericInput(x,x,30)})
})})
ui <- bootstrapPage(
fluidRow(
column(4,offset = 2,
tags$h4("numeric inputs"),
uiOutput('mtcars_numerics') # These will be all the numeric inputs for mtcars
),
column(6,
tags$h4("current input values"),
verbatimTextOutput('show_vals') # This will show the current value and id of the inputs
)
)
)
server <- function(input, output, session){
# creates the output UI elements in the loop
output$mtcars_numerics <- renderUI({
tagList(lapply(colnames(mtcars), function(i){ # must use `tagList` `
column(3,
numericInput(
inputId = sprintf("mt_col_%s",i), # Set the id to the column name
label = toupper(i), # Label is upper case of the col name
min = min(mtcars[[i]]), # min value is the minimum of the column
max = max(mtcars[[i]]), # max is the max of the column
value = mtcars[[i]][[1]] # first value set to the first row of the column
))
})
)
})
# So we can see the values and ids in the ui for testing
output$show_vals <- renderPrint({
all_inputs <- names(session$input)
input_vals <- plyr::ldply(all_inputs, function(i){
data.frame(input_name = i, input_value = input[[i]],stringsAsFactors = FALSE)
})
input_vals
})
}
shinyApp(ui, server)
Results in:

Dynamic select input not working with loaded data

Using R shiny, I am developing a simple app that allows user to input data from a Rdata file. I want the app to load the data, show the names of numeric variables in a select input field, and after the user selected one of variables do some analysis. But I can not get it working. In the code provided I obtain two outputs: summary, which works fine, and the MEAN of the selected variable which I can not get work.
server.R
library(shiny)
library(shinydashboard)
library(data.table)
library(DT)
shinyServer(function(input, output) {
#### DATA LOAD
df <- reactive({
df <- input$datafile
if (is.null(df)) {
# 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
df<-data.table(df)
})
#### SELECTS
num <- reactive({
num <- sapply(df(),is.numeric)
num <- names(num)
})
output$var_num <- renderUI({
vector.num <- as.vector(num())
selectInput("var_num", "Select Variables :", as.list(vector.num), multiple = FALSE)
})
#### OUTPUTS
### SUMMARY
output$summary_num <-renderDataTable({
x<-t(sapply(df(), summary))
x<-as.data.frame(x)
x<-setDT(x, keep.rownames = TRUE)[]
colnames(x) <- c("Variable","Mínimo","1er Quartil", "Mediana", "Media", "3er Quartil","Máximo")
datatable(x)
})
### MEAN OF SELECTED VAR
output$test <-renderPrint ({
if(is.null(df()))
return()
dat<- df()
dat <- dat[,num(), drop = FALSE]
mean(dat[,input$var_num])
})
})
UI.R
dashboardPage(
dashboardHeader(title = "TITLE", titleWidth = 500),
dashboardSidebar(disable = TRUE), #---> fin SIDEBAR
dashboardBody(
fluidRow(
box(width=12, status = "primary",
tabsetPanel(
tabPanel("Test",
fileInput("datafile", label = h3("File input")),
uiOutput("var_num"),
br(),hr(),br(),
fluidRow(column(width=4, uiOutput("var_caracter"),textOutput("test"))),
br(),hr(),br(),
fluidRow(column(width=8, "Variables Numericas", dataTableOutput("summary_num")))
)
) # fin tabsetPanel
) # fin box
)# fin fluidRow
)# fin dashboardBody
)# fin dashboardPage
When I run the app everything goes fine (select input, summary, etc) except the calculation and printing of the MEAN of the selected variable. I guess for some reason the subsetted dataframe is empty, but I do not know why...
Any help will be great! Thanks in advance.
I get it working.
The solution was to define the dataset I used as.data.frame:
### MEAN OF SELECTED VAR
output$test <-renderPrint ({
if(is.null(df()))
return()
dat<- as.data.frame(df()) ## THIS IS THE CORRECTION
dat <- dat[,num(), drop = FALSE]
mean(dat[,input$var_num])
})
I do not really understand why... The reactive file df() was defined as data.table and dat shoul inherit that, but for some reason it was necesary an explicit definition as dataframe.

R shiny ERROR: object of type 'closure' is not subsettable [duplicate]

This question already has answers here:
Error in <my code> : object of type 'closure' is not subsettable
(6 answers)
Closed 8 years ago.
I am using the following code and I always get the this subsettable error.
What am I subsetting and where am I wrong.
This should be some basic entry code that I modified and which did
work at some point and I can't see the error.
Thank you
server.R
library(shiny)
# Define a server for the Shiny app
shinyServer(function(input, output) {
# Filter data based on selections
output$table <- renderDataTable({
data <- read.table("my.csv", sep =',', header =TRUE)
if (input$shortdesc != "All"){
data <- data[data$ShortDescription == input$shortdesc,]
}
if (input$taken != "All"){
data <- data[data$Taken == input$taken,]
}
if (input$location != "All"){
data <- data[data$Location == input$location,]
}
data
})
})
ui.R
library(shiny)
# Define the overall UI
shinyUI(
fluidPage(
titlePanel("My Items"),
# Create a new Row in the UI for selectInputs
fluidRow(
column(4,
selectInput("man",
"What:",
c("All",
unique(as.character(data$ShortDescription))))
),
column(4,
selectInput("trans",
"Where:",
c("All",
unique(as.character(data$Location))))
),
column(4,
selectInput("cyl",
"Who:",
c("All",
unique(as.character(data$Taken))))
)
),
# Create a new row for the table.
fluidRow(
dataTableOutput(outputId="table")
)
)
)
Update:
Why does the example (see below) work and the moment I change it to my.csv it breaks ?
If "data" is a buildin function wouldn't that collide also with the example below ?
Sorry for not understanding, but this puzzles me.
server.R
library(shiny)
# Load the ggplot2 package which provides
# the 'mpg' dataset.
library(ggplot2)
# Define a server for the Shiny app
shinyServer(function(input, output) {
# Filter data based on selections
output$table <- renderDataTable({
data <- mpg
if (input$man != "All"){
data <- data[data$manufacturer == input$man,]
}
if (input$cyl != "All"){
data <- data[data$cyl == input$cyl,]
}
if (input$trans != "All"){
data <- data[data$trans == input$trans,]
}
data
})
})
ui.R.
library(shiny)
# Load the ggplot2 package which provides
# the 'mpg' dataset.
library(ggplot2)
# Define the overall UI
shinyUI(
fluidPage(
titlePanel("Basic DataTable"),
# Create a new Row in the UI for selectInputs
fluidRow(
column(4,
selectInput("man",
"Manufacturer:",
c("All",
unique(as.character(mpg$manufacturer))))
),
column(4,
selectInput("trans",
"Transmission:",
c("All",
unique(as.character(mpg$trans))))
),
column(4,
selectInput("cyl",
"Cylinders:",
c("All",
unique(as.character(mpg$cyl))))
)
),
# Create a new row for the table.
fluidRow(
dataTableOutput(outputId="table")
)
)
)
Expanding on #Roland 's comment: you have a namespace collision going on. There's a function data in base R, so if R can't find an object data in the current environment, the function data is referenced from the global environment. In your particular case, this happens because ui.R and server.R are in different environments, and, moreover, the individual function bodies all have their own environments. So the data in fluidRow(...) doesn't reference the datafrom output$table. You need to pass around arguments and/or dynamically construct the UI using the functions for that. See for example here.
Update for the updated question:
Replacing datawith mpg in ui.R fixes the problem because mpg is defined as a dataset in the global environment (this is a side effect of library(ggplot2)). So mpg is (almost) always accessible and has the necessary properties. For a fairer comparison, replace mpg in ui.R with data, which should bring back the old problem, because data in the global environment refers to a function and not the data frame you're trying to manipulate.
Super Update with more general solution for dynamically defining and loading selection elements for each dataset:
The server code loops through all the columns of the chosen dataframe and dynamically generates a selection box for every column that has a type other than double. (Uniqueness and equality with doubles is just asking for trouble.) This avoids the scoping issues because the UI elements are created in server.R after a call to the reactive function that loads the data.
server.R
library(shiny)
library(ggplot2)
# Define a server for the Shiny app
shinyServer(function(input, output) {
get.data <- reactive({
switch(input$dataset,
"rock" = rock,
"pressure" = pressure,
"cars" = cars,
"mpg" = mpg,
"mtcars" = mtcars,
"diamonds" = diamonds)
})
# Filter my.data based on selections
output$table <- renderDataTable({
my.data <- get.data()
for(n in names(my.data)){
# avoid too many cases ...
# unique() with double is just asking for trouble
if(typeof(my.data[,n]) != "double"){
val <- eval(parse(text=paste0("input$",n)))
print(val)
if(val != "All"){
my.data <- eval(parse(text=paste0("subset(my.data,",n,"==",val,")")))
}
}
}
my.data
})
output$dyn.ui <- renderUI({
my.data <- get.data()
sel <- NULL
for(n in names(my.data)){
# avoid too many cases ...
# unique() with double is just asking for trouble
if(typeof(my.data[,n]) != "double"){
sel <- c(sel,
selectInput(n, n, choices=c("All",unique(my.data[,n])))
)
}
}
sel
})
})
ui.R
library(shiny)
# Define the overall UI
shinyUI(fluidPage(
titlePanel("Displaying tables dynamically with renderUI() and eval()"),
sidebarLayout(
sidebarPanel(h2("Selection"),
selectInput("dataset", "Dataset", c("rock", "pressure", "cars","mtcars","diamonds")),
# Create a new Row in the UI for selectInputs
uiOutput("dyn.ui")
)
,mainPanel(h2("Data"),
dataTableOutput(outputId="table")
)
)
))

Resources