首页 > 解决方案 > R/Shiny - 将复选框标签转移到功能字段

问题描述

我需要选中的复选框标签来填写“[,c("checkbox1","checkbox2")]" 字段(其中写有“checkbox1”和“checkbox2”)。谢谢你。

这是我的代码。

library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(readxl)
library(tidyverse)
library(readxl)
library(stringr)

ui <- fluidPage(
    
    br(),
    
    fileInput("archive", "Upload file", accept = c(
        ".xlsx")),

        # Itens Selection
    checkboxGroupInput("additem", "Select Items", choices = NULL)
        )
    box(
        width = 2000,
        verbatimTextOutput("calfa")
)

server <- function(input, output, session) {
    
        # Upload Data Sheet
    
    csv <- reactive({
        req(input$archive)
        inFile <- input$archive
        df <- read_xlsx(inFile$datapath)
        return(df)
    })
    
        #reactive value that will hold the name of the file
    reactive_my_path <- reactive({
        # Test if file is selected
        req(input$archive)
        return(sub(".xlsx$", "", basename(input$archive$name)))
    })
    
    observe({
        input$archive
        # update the choices in input$additem
        updateCheckboxGroupButtons(session,
                                   "additem",
                                   paste('Column names in:', reactive_my_path()),
                                   choices = names(csv()))
    })
    
        # Alpha
    output$calfa <-
        renderPrint({
            int<-csv()[,c("checkbox1","checkbox2")]
            int <- na.omit(int) 
            psych::alpha(int, check.keys = TRUE) 
        })
}

# App

shinyApp(ui, server)

标签: rcheckboxshiny

解决方案


您可以使用input$additem包含所有选中的复选框。此外,我还包含了另一个条件,psych::alpha仅当有多个列时才运行代码。

library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(readxl)
library(tidyverse)
library(readxl)
library(stringr)

ui <- fluidPage(
  
  br(),
  
  fileInput("archive", "Upload file", accept = c(
    ".xlsx")),
  
  # Itens Selection
  checkboxGroupInput("additem", "Select Items", choices = NULL),
  box(
    width = 2000,
    verbatimTextOutput("calfa")
  )
)


server <- function(input, output, session) {
  
  # Upload Data Sheet
  
  csv <- reactive({
    req(input$archive)
    inFile <- input$archive
    df <- read_xlsx(inFile$datapath)
    return(df)
  })
  
  #reactive value that will hold the name of the file
  reactive_my_path <- reactive({
    # Test if file is selected
    req(input$archive)
    return(sub(".xlsx$", "", basename(input$archive$name)))
  })
  
  observe({
    input$archive
    # update the choices in input$additem
    updateCheckboxGroupButtons(session,
                               "additem",
                               paste('Column names in:', reactive_my_path()),
                               choices = names(csv()))
  })
  
  # Alpha
  output$calfa <-
    renderPrint({
      req(length(input$additem) > 1)
      int<-csv()[,input$additem]
      int <- na.omit(int) 
      psych::alpha(int, check.keys = TRUE) 
    })
}

# App

shinyApp(ui, server)

推荐阅读