根据闪亮的应用程序中另一个数据表的单元格选择创建数据表

时间:2018-07-08 19:50:16

标签: r shiny dt

我有一个简单的闪亮应用程序,具有2个datable。

#ui.r
navbarPage(
  "Application",
  tabPanel("General",
           sidebarLayout(

             sidebarPanel(
              ),
             mainPanel(
               DT::dataTableOutput("hot3"),
               br(),
               DT::dataTableOutput("hot5")
             )
           )))
#server.r
library(shiny)
library(DT)
server <- function(input, output,session) {

   DF= data.frame(Sel. = rep(TRUE,2),
               Label=paste("Test",as.integer(1:2)),
               Marg=rep("Marg1",2),
               Avail.=as.integer(rep.int(50,2)),
               Sel =as.integer(rep.int(50,2)),
               stringsAsFactors = FALSE)

  output$hot3 <-DT::renderDataTable(
    DF,
    selection=list(mode="single", target="cell")
  )
    output$hot5 <-DT::renderDataTable({
      DF = data.frame(
        Sel= rep(TRUE, as.numeric(input$hot3_cells_selected)),
        Id= 1:as.numeric(input$hot3_cells_selected),
        Label=paste("Item",as.integer(1:as.numeric(input$hot3_cells_selected))),
        Pf=as.integer(rep.int(0,as.numeric(input$hot3_cells_selected))),
        stringsAsFactors = FALSE)
      DF
    })


}

我想要实现的是,当我单击“可用”单元格(50)创建具有50 rpws的新数据帧时,该数据帧将显示在新数据表中。 enter image description here

但我认为是错误

Error in rep: invalid 'times' argument

1 个答案:

答案 0 :(得分:1)

由于您没有提供有效的rep参数,因此times函数引发了此错误。在这种情况下,input$hot3_cells_selected返回一个向量,分别代表所选单元格的行索引和列索引。您可以使用以下命令访问单元格的实际内容:

DF[input$hot3_cells_selected]

但是,您需要进行一些其他调整以使代码更健壮。例如,input$hot3_cells_selected为空,直到选择了一个单元格,这将与rep函数引起类似的问题。或者,您应该涵盖选择了非数字单元格的情况(即 Test1 Marg1 )。下面是一个可能的简单解决方案:

# changing only this part of the code will be enough
# inserted DF[input$hot3_cells_selected] when needed below
output$hot5 <-DT::renderDataTable({
    # checking whether any cell is selected or not
    if(length(input$hot3_cells_selected) > 0) {
      # checking whether the selected cell includes a number or not
      # note that suppressWarnings is optional
      if(!is.na(suppressWarnings(as.numeric(DF[input$hot3_cells_selected])))) {
        # you don't need to store the data frame, so removed the assignment
        # even if you wanna store it for future reference, use a unique name (not DF)
        data.frame(
          Sel= rep(TRUE, as.numeric(DF[input$hot3_cells_selected])),
          Id= 1:as.numeric(DF[input$hot3_cells_selected]),
          Label=paste("Item",as.integer(1:as.numeric(DF[input$hot3_cells_selected]))),
          Pf=as.integer(rep.int(0,as.numeric(DF[input$hot3_cells_selected]))),
          stringsAsFactors = FALSE
        )
      }
    }
  })