Dee
Dee

Reputation: 19

Selecting data from a drop down list in R

I have a created a data frame (df) and populated it with numbers in the first row in shiny R. Now I would like to see the index of each variable element of the data frame in a drop down list when I upload a file. In other words I would like to use the index to select elements rather than the column names. I know this may seem weird to ask but I really need help with this. My sample code is below:

 **ui.R**

 shinyUI(fluidPage(
 titlePanel(""),
 sidebarLayout(
 sidebarPanel(
  fileInput("file", "Upload the file", 
            accept=c('txt', 'text files', '.txt')),
  tags$hr(style="padding:0px;margin:0px"),
  selectInput(inputId = "table_no", label = "Select table", choices = "Pending Upload"),

  ),


 **server.R**
 shinyServer(function(input, output, session){ 

 data <- reactive({
 file1 <- input$file
 if(is.null(file1)){return()}
 dta <- read.csv(file1$datapath, header = TRUE, fill = TRUE)

 trial <- 1:5
 df <- data.frame(matrix(trial, ncol = length(trial), nrow = 1, byrow = TRUE), stringsAsFactors = FALSE)
 colnames(df) <- paste("Table",trial)

Upvotes: 0

Views: 2561

Answers (1)

GyD
GyD

Reputation: 4072

You can use the index instead of the column names the same way you can subset by column indices in R. The only difference in shiny is that the value of selectInput is a string so you have to use as.numeric().

Simple workflow:

  1. Populate the selectInput with column indices using the column count: 1:ncol(data())
  2. Subset a data.frame using data()[, as.numeric(input$table_no)]

I used the iris dataset for presentation purposes. It will also work with a reactive value.

Example:

library(shiny)

ui <- fluidPage(
  selectInput("table_no", "", choices = 1:ncol(iris)),
  tableOutput("tbl")
)

server <- function(input, output, session) {
  output$tbl <- renderTable( {
    index <- as.numeric(input$table_no)
    colname <- colnames(iris)[index]

    out <- data.frame(iris[, index])
    colnames(out) <- colname

    out
  })
}

shinyApp(ui, server)

Also as Samuel pointed out, make sure you check out how to create a reproducible example: How to make a great R reproducible example?

Upvotes: 1

Related Questions