在R Shiny中创建带有复选框的网格

时间:2018-08-08 11:52:00

标签: r shiny shinyjs shiny-reactivity

我正在尝试创建一个网格,该网格的行和列名作为特定数据集中的变量,以便我可以映射单个行以在后端的r中进行回归(其中行名将是因变量,列名将是自变量)。任何人都可以帮助解决该问题。

I am trying to get something like this on my app. when a user selects lets say app and alerts and when he presses the submit button it does the regression on the backend i.e website ~ app + alerts

我现在没有任何代码,因为我对R Shiny非常陌生,不知道如何使用复选框创建此网格。如果有人可以指导我如何进行操作,那将非常有帮助。

谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用DT包创建带有复选框(或其他活动元素)的表。请参见下面的代码(基于"Showing as Checkbox" anwser

library(shiny)
library(DT)

# create data.frame of row/column names of futre datable
my_df <- data.frame(nam = c("Favorite1", "Favorite2"))

runApp(
  list(
    ui = fluidRow(
      sidebarLayout(
      h2("Checkboxes Datatable"),
      DT::dataTableOutput("mytable", width = "1%")),
      mainPanel(h2("Selected"),
      tableOutput("checked"))
    ),
    server = function(input, output) {

    # helper function for making checkbox
    shinyInput <- function(FUN, len, id, ...) { 
      inputs <- character(len) 
      for (i in seq_len(len)) { 
        inputs[i] <- as.character(FUN(paste0(id, i), label = NULL, ...)) 
      } 
      inputs 
    } 
    # datatable with checkbox
    output$mytable <- DT::renderDataTable( 
      expr = {
        df <- data.frame(
        #  my_df,
          my_df,
          Favorite1 = shinyInput(checkboxInput, nrow(my_df), "cbox1"), 
          Favorite2 = shinyInput(checkboxInput, nrow(my_df), "cbox2")
        )
        names(df)[1] <- " "
        df
      }, 
      rownames = FALSE,
      server = FALSE, 
      escape = FALSE, 
      options = list(
        ordering = FALSE,
        searching = FALSE,
        paging = FALSE,
        info = FALSE,
        preDrawCallback = JS("function() { 
          Shiny.unbindAll(this.api().table().node()); }"
        ), 
        drawCallback = JS("function() { 
          Shiny.bindAll(this.api().table().node()); } "
        ) 
      )
    )

    # helper function for reading checkbox
    shinyValue <- function(id, len) { 
      unlist(
        x = lapply(
          X = seq_len(len), 
          FUN = function(i) { 
            value = input[[paste0(id, i)]] 
            if (is.null(value)) {
              NA
            } else {
              value
            }  
          }
        )
      ) 
    } 
    # output read checkboxes
    output$checked <- renderTable({
      data.frame(
        Favorite1 = shinyValue("cbox1", nrow(my_df)),
        Favorite2 = shinyValue("cbox2", nrow(my_df))
      )
    }
  )
 }
  )
)

输出(上方表格中单击的复选框在下方显示其状态): Checkboxes