从R中的下拉列表中选择数据

Selecting data from a drop down list in R

我创建了一个数据框 (df) 并在 shiny R 的第一行中填充了数字。现在我想在下拉列表中看到数据框的每个变量元素的索引我上传一个文件。换句话说,我想使用 select 元素的索引而不是列名。我知道问这个问题可能看起来很奇怪,但我真的需要这方面的帮助。我的示例代码如下:

 **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)

您可以使用索引而不是列名,就像您可以在 R 中按列索引进行子集化一样。闪亮的唯一区别是 selectInput 的值是一个字符串,因此您必须使用as.numeric().

简单的工作流程:

  1. 使用列数用列索引填充 selectInput1:ncol(data())
  2. 使用 data()[, as.numeric(input$table_no)]
  3. data.frame 进行子集化

我使用 iris 数据集进行演示。它也适用于反应值。

示例:

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)

正如 Samuel 指出的那样,请务必查看如何创建可重现的示例:How to make a great R reproducible example?