动态制作数据框,以获取列中的值和GUI中的值

时间:2019-12-17 11:02:33

标签: r shiny

我有一本具有三个不同工作表的Excel工作簿。它们看起来像这样:sheet1sheet2sheet3

这是我的代码:

library(shiny)
library(readxl)
library(tidyverse)

ui <- fluidPage(
  fileInput("config","Load Configuration File",accept =c('.xls',',xlsx')),
  actionButton("show_fields","Show Fields"),
  actionButton("estimate","Estimate"),
  uiOutput("ui"),
  textOutput("prod")


)
server <- function(input,output) {

  read_excel_allsheets <- function(filename, tibble = FALSE) {
    sheets <- readxl::excel_sheets(filename)
    x <- lapply(sheets, function(X) readxl::read_excel(filename, sheet = X))
    if(!tibble) x <- lapply(x, as.data.frame)
    names(x) <- sheets
    return(x)
  }


  sheets <- reactive({read_excel_allsheets(input$config$datapath)})
  design <- eventReactive(input$show_fields, {
    fluidPage(
      numericInput("size","Size",value = 0),
      lapply(names(sheets()), function(sheet) {
        conf <- eval(parse(text = paste("sheets()$",sheet))) %>% column_to_rownames(., var = "Rows")
        lapply(1:nrow(conf),function(i) {
          selectInput(row.names(conf)[i],label = row.names(conf)[i],choices = colnames(conf))
        })
      })

    )
  })
  output$ui <- renderUI({design()})

  mul <- eventReactive(input$estimate, {
    sapply(names(sheets()), function(sheet) {
      conf <- eval(parse(text = paste("sheets()$",sheet))) %>% column_to_rownames(., var = "Rows")
      sapply(1:nrow(conf), function(j) {
        conf[row.names(conf)[j],eval(parse(text = paste0("input$`",row.names(conf)[j],"`",sep = "")))]
      })
    })

  })

  #output$prod <- renderPrint({paste("Product is: ",prod(mul(),na.rm = TRUE)*input$size)})
  product <- reactive({
    if(length(sheets()) == 1) {
      prod(mul(),na.rm = TRUE)*input$size
    }
    else {
      a <- sapply(names(sheets()), function(sheet){
        prod(eval(parse(text = paste("mul()$",sheet))),na.rm = TRUE)
      })
      prod(a)*input$size
    }
  })

  output$prod <- renderPrint({product()})
}

shinyApp(ui=ui,server = server)

在运行此代码时,您将获得如下所示的ui: APP

当您选择具有多张工作表的excel工作簿时,它将显示大小为numericInput,所有这些行显示为下拉(selectInput)名称,并显示列名作为选择。在为size赋予一定的值并选择下拉菜单后,它将显示size的乘积以及excel工作簿中的所有相应值。

所以现在我想要什么:

1:我希望使用这些数字,然后选择“输入”填充为多列(2或3)。

2:我现在想在下面同一页上的表格中显示一个具有所有选定值,大小和乘积的数据框。我无法形成具有所有值的数据框。数据框中的列名称应与大小以及所有其他下拉名称相同。同样,当我更改下拉列表或大小中的值时,该表还应附加下一组值。

0 个答案:

没有答案