问题
I'm trying to have the user upload a .csv file, then take a column (factor) of that .csv file and create user input of to determine which of the unique names in that field will be selected for the data frame.
So if I have the following example data.frame:
COURSE VALUE
1 A 7
2 C 2
3 C 2
4 B 9
...
I'd want to filter using Select_Input and the user can select select say A and C and the data frame would be filtered for just rows with A and C. Below is the code to generate the UI for the select_Input
output$choose_course<-renderUI{
# If missing input, return to avoid error later in function
if(is.null(input$model.input))
return()
# Get the data set with the appropriate name
course.names <-c("All",as.vector(t(unique(select_(model.data0(),"COURSE")))))
selectInput("courses","Choose courses", choices=course.names, multiple=TRUE)
}
Note that model.data0() is the reactive data entered by the user via a .csv file. This first part of code works ok (but maybe the format is messing up the next stuff?) and displays for the user input selections. And next we have my attempt at filtering from the selectInput...
model.data<-reactive({
if(is.null(input$model.input))
return()
localdata<-model.data0()
if(input$courses!="All"){
localdata<-localdata[localdata$COURSE==unlist(input$courses),]
}
})
However, this returns an error of "argument 1 (type 'list') cannot be handled by 'cat' ". I tried the unlist above to change it to a vector but didn't seem to work. Any ideas how I can make this filter my data?
回答1:
You could try doing this:
require(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
uiOutput('choose_course')
),
mainPanel(
tableOutput('courseTable')
)
)
)
server <- function(input, output, session) {
# Build data, would be replaced by the csv loading in your case
n <- 10
model.data0 <- reactive ({
data.frame( "COURSE" = sample(LETTERS[1:3], n, replace=TRUE),
"VALUE" = sample(1:10, n, replace=TRUE))
})
# Render selectInput
output$choose_course <- renderUI({
course.names <- as.vector( unique(model.data0()$COURSE) )
selectInput("courses","Choose courses", choices=course.names, multiple=TRUE)
})
# Subset so that only the selected rows are in model.data
model.data <- reactive({
subset(model.data0(), COURSE %in% input$courses)
})
output$courseTable <- renderTable({ model.data() })
}
runApp(shinyApp(ui,server))
来源:https://stackoverflow.com/questions/37887482/filtering-from-selectinput-in-r-shiny