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

从R中的下拉列表中选择数据,r,shiny,shiny-server,R,Shiny,Shiny Server,我已经创建了一个数据框(df),并在Shinny R的第一行中用数字填充它。现在我想在上传文件时在下拉列表中查看数据框的每个变量元素的索引。换句话说,我想使用索引来选择元素,而不是列名。我知道这问起来很奇怪,但我真的需要帮助。我的示例代码如下: **ui.R** shinyUI(fluidPage( titlePanel(""), sidebarLayout( sidebarPanel( fileInput("file", "Upload the file",

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

 **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)
**ui.R**
shinyUI(fluidPage)(
标题板(“”),
侧边栏布局(
侧栏面板(
文件输入(“文件”,“上传文件”,
accept=c('txt','text files','.txt'),
标记$hr(style=“padding:0px;margin:0px”),
选择输入(inputId=“表号”,label=“选择表”,choices=“待上传”),
),
**服务器.R**
shinyServer(函数(输入、输出、会话){

数据您可以使用索引而不是列名,方法与在R中按列索引子集的方法相同。唯一的区别是
selectInput
的值是字符串,因此您必须使用
as.numeric()

简单工作流程:

  • 使用列计数用列索引填充
    selectInput
    1:ncol(data())
  • 子集a
    data.frame
    使用
    data()[,as.numeric(输入$table\u no)]
  • 我将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)
    
    库(闪亮)
    
    你能提供一个用户界面吗?你的解决方案很有帮助。谢谢!