R闪亮应用程序中使用复选框进行多项选择以进行数据子集

时间:2017-11-22 06:38:45

标签: r shiny

我试图仅显示选中的复选框数据,以便在复选框面板上显示UI,其中前三个复选框彼此互斥(即,只能从前三个中选择一个,并且可以从中选择一个KPI的数量)复选框选项)在闪亮的应用程序,但努力解决这个问题。根据复选框中的用户选择,图表应自动更改,例如MO_ID和&之间的单独线条图。每种选择药物或制造商或药物类别垂直选择的KPI数量。我尝试在下面执行此操作是我的代码,您的帮助将受到高度赞赏

DrugData.csv

MO_ID   capture_rate_high_adj   NBRx_adjusted_high_share    Total_adjusted_high_share   TRx_baseline_low_share  DrugType    DrugClass   MANUFACTURER        date    goal1completions    goal
1212016 0.097167749 0.020752878 0.003667932 0.00225614  DRUG 1  ART Manufacturer5       1012016 4   goal1
1612011 0.216740195 0.041761676 0.008145028 0.004881227 DRUG 1  II  Manufacturer4       1012016 10  goal2
10112016    0.679445079 0.13818709  0.033960635 0.020129843 DRUG 1  NNRTI   Manufacturer3       1012016 8   goal3
512016  0.532274828 0.113680095 0.030975403 0.018364531 DRUG 2  PI  Manufacturer2       1012016 13  goal5
1012015 0.541738943 0.122225515 0.036405199 0.021408197 DRUG 3  STR Manufacturer1       1012016 6   goal4
1012015 0.323315694 0.08475766  0.026376663 0.015392466 DRUG 4  NNRTI   Manufacturer5       1012016 12  goal7
1012014 0.426477779 0.100488819 0.034437931 0.020072081 DRUG 1  PI  Manufacturer4       1012016 7   goal6
1012016 0.627661362 0.146335677 0.052207204 0.030324811 DRUG 2  STR Manufacturer3       1012016 12  goal6
2712016 0.682537914 0.173016511 0.067592392 0.039461229 DRUG 3  NNRTI   Manufacturer2       1012016 10  goal7
1712016 0.395454954 0.106938038 0.043405249 0.025173052 DRUG 4  PI  Manufacturer1       1012016 10  goal8
1012016 0.405448121 0.097840719 0.042806791 0.024596638 DRUG 1  STR Manufacturer5       1012016 10  goal9
1812016 0.61654553  0.154245245 0.080707769 0.046582374 DRUG 2  NNRTI   Manufacturer4       1012016 10  goal10
1912016 0.448994855 0.082140864 0.049786133 0.028663422 DRUG 3  PI  Manufacturer3       1012016 10  goal11
2012016 0.563174269 0.103926623 0.06641121  0.038270423 DRUG 4  STR Manufacturer2       1012016 10  goal12
2112016 0.294613984 0.062050611 0.041020625 0.023675833 DRUG 1  ART Manufacturer1       1012016 10  goal13
2212016 0.408718205 0.075283165 0.0575669   0.03282064  DRUG 2  II  Manufacturer5       1012016 10  goal14
2312016 0.111911856 0.018734629 0.015831974 0.009130108 DRUG 3  NNRTI   Manufacturer4       1012016 10  goal15
2412016 0.150495864 0.026025458 0.024094392 0.013900663 DRUG 4  PI  Manufacturer3       1012016 10  goal16

我的代码

我还尝试从文件夹中通过下拉菜单选择相同格式的任何文件.csv文件来更改分析数据,但有些文件无法正常工作。非常感谢您的帮助。

###############Assigning Packages
library(shiny)
library(dplyr)
library(DT)
library(plotly)
library(rhandsontable)

#############################
# Importing Data
cDat <- read.table(file = "data/DrugData.csv", sep = ",",  header =

                 TRUE, row.names = NULL)
cDat1 <- read.table(file = "data/DrugData1.csv", sep = ",",  header =

                 TRUE, row.names = NULL)
DF <- read.csv("/Users/anshulujlayan/Documents/output.csv", sep=",", 
 row.names=1)
    #( DF <- data.frame(Value = 1:10, Name = LETTERS[1:10],
    #                   Date = seq(from = Sys.Date(), by = "days", length.out =     10),
 #                  stringsAsFactors = FALSE) )
    editTable(DF, outdir="/Users/anshulujlayan/Documents",         outfilename="newaakritiDF")
############################
    #filenames <- list.files(path = "input$files[['data/']]", pattern=     "*.csv" )
    folder <-         "/Users/anshulujlayan/Documents/Team_Profile/First_Assignement_29_September_2017    /data"      # path to folder that holds multiple .csv files
filenames <- list.files(path=folder, pattern="*.csv")
print(filenames)


print(DF)
MANUFACTURER_list <- unique(cDat$MANUFACTURER)
DrugClass_list <- unique(cDat$DrugClass)
DrugType_list <- unique(cDat$DrugType)
columns <- names(cDat)
abc <- cDat$MO_ID

d <- as.character(cDat$MO_ID)
d <-  paste0(substr(d, 0, 2), "-", substr(d, 3, 4), "-", substr(d, start = 4, 7))
cDat$MO_ID <- as.Date(d, format = "%d-%m-%y")
mno <- cDat$filteredData
HL_list <- c("High","low")
print(mno)

editTable <- function(DF, outdir=getwd(), outfilename="newAakritiDF"){
server <- function(input, output, session) {

  values <- reactiveValues()

  ## Handsontable
  observe({
    if (!is.null(input$hot)) {
      values[["previous"]] <- isolate(values[["DF"]])
      DF = hot_to_r(input$hot)
    } else {
      if (is.null(values[["DF"]]))
    DF <- DF
      else
    DF <- values[["DF"]]
    }
    values[["DF"]] <- DF
  })

  output$hot <- renderRHandsontable({
    DF <- values[["DF"]]

    rhandsontable(DF)
  })

  ## Save
  observeEvent(input$save, {
    fileType <- isolate(input$fileType)
    finalDF <- isolate(values[["DF"]])
    dput(finalDF, file=file.path(outdir, sprintf("%s.txt", outfilename)))
    # saveRDS(finalDF, file=file.path(outdir, sprintf("%s.rds",     outfilename)))
  }
  )



  inputdata <- reactive({
    if (grepl("[/\\\\]", input$dataset)) {
      stop("Invalid dataset")
    }
    read.csv(file.path("folder", input$dataset))
  })

  filteredData <- reactive({
    cDat %>% filter(MANUFACTURER %in% input$campaign &
                  DrugClass %in% input$campaign1 &
                  DrugType %in% input$campaign2 )
  })


  selectedData <- reactive({
    filteredData() %>% 
      select_(.dots = input$columns)
  })

  output$mytable1 <- renderDataTable({
    selectedData()


  })



  output$downloadData <- downloadHandler(
    filename = function() { 
      "DrugDataab.csv"
    },

    content = function(file) {
      write.table(x = selectedData(),
              file = file,
              quote = FALSE, sep = ",", row.names = FALSE)
    }
  ) 
  observe({
    if(input$selectall == 0) return(NULL) 
    else if (input$selectall%%2 == 0)
    {
              updateCheckboxGroupInput(session,"campaign","",choices=MANUFACTURER_list)
    }
    else
    {
                  updateCheckboxGroupInput(session,"campaign","",choices=MANUFACTURER_list,selecte    d=MANUFACTURER_list)
    }
  })

  observe({
    if(input$selectall2 == 0) return(NULL) 
    else if (input$selectall2%%2 == 0)
    {
          updateCheckboxGroupInput(session,"campaign1","",choices=DrugClass_list)
    }
    else
    {
      updateCheckboxGroupInput(session,"campaign1","",choices=DrugClass_list,selected=    DrugClass_list)
    }
  })

  observe({
    if(input$selectall3 == 0) return(NULL) 
    else if (input$selectall3%%2 == 0)
    {
      updateCheckboxGroupInput(session,"campaign2","",choices=DrugType_list)
    }
    else
    {
      updateCheckboxGroupInput(session,"campaign2","",choices=DrugType_list,selected=D    rugType_list)
    }
  })


  observe({
    if(input$selectall4 == 0) return(NULL) 
    else if (input$selectall4%%2 == 0)
    {
      updateCheckboxGroupInput(session,"columns","",choices=columns)
    }
    else
{
          updateCheckboxGroupInput(session,"columns","",choices=columns,selected=columns)
    }
  })

  output$plot <- renderPlotly({
    plot_ly(cDat, x = ~abc, y = ~columns)
  })

  filterednewData <- reactive({ 
    # no need for "filter"
    cDat[cDat$MANUFACTURER %in% input$checkGroup, ]
  })

  output$Conversionrate1 <- renderPlotly({
    # use filteredData() instead of the full dataset
    plot_ly(
      filteredData(),  
      x = ~MO_ID,
      y = ~goal1completions,
      split = ~MANUFACTURER,
      mode = "lines + markers",
      hoverinfo = "y" # "y" instead of y ... at least in the newest version
    ) 
  })

}


####################### UI.R ##############


ui <- fluidPage(
  # Application title
  titlePanel("Forecasting Engine"),
  # Sidebar with a slider input for the number of bins
  sidebarLayout(
    sidebarPanel(style = "background-color: #98d8c6",

             fluidRow(


               column(6,
                      h6(style = "font-weight: bold;color: #275c4d","Manufacture"),
                      div(style = "height: 200px; background-color:white; max-height: 200px; border: 1px solid rgba(128, 128, 128, 0.52); padding-left: 10px",
                          br(),
                          checkboxGroupInput('campaign', 'Manufacturer',
                                             MANUFACTURER_list,
                                             selected = MANUFACTURER_list)

                      )
               ),
               column(6,
                      h6(style = "font-weight: bold;color: #275c4d","Drug Class"),
                      div(style = "overflow-y: scroll; max-height: 200px; min-height: 200px; background-color:white;padding-left: 10px;border: 1px solid rgba(128, 128, 128, 0.52);",
                          checkboxGroupInput('campaign1', 'DrugClass',
                                             DrugClass_list,
                                             selected = DrugClass_list)

                      )
               )
             ),
             fluidRow(
               column(6, 
                      h6(style = "font-weight: bold;color: #275c4d","Drug List"),
                      div(style = "overflow-y:scroll;border: 1px solid rgba(128, 128, 128, 0.52); max-height: 200px; min-height: 200px; background-color:white; padding-left: 10px",
                          br(),
                          checkboxGroupInput('campaign2', 'DrugType',
                                             DrugType_list,
                                             selected = DrugType_list))),
               column(6,
                      h6(style = "font-weight: bold;color: #275c4d","KPI"),
                      div(style = "overflow-y:scroll;border: 1px solid rgba(128, 128, 128, 0.52); max-height: 200px; min-height: 200px; background-color:white;padding-left: 10px",
                          # checkboxGroupInput("columns","Select Columns",choices=vchoices,inline = T)
                          checkboxGroupInput('columns', 'Columns',
                                             columns,
                                             selected = columns))



               )),br(),

             fluidRow(
               column(3,actionLink(style="background-color: #275c4d;color: #fff;width: 150px","selectall","ALL")),
               column(3,actionLink(style="background-color: #275c4d;color: #fff;width: 50px","selectall2","RESET")),
               column(3,actionLink(style="background-color: #275c4d;color: #fff;width: 50px","selectall3","ALL")),
               column(3,actionLink(style="background-color: #275c4d;color: #fff;width: 50px","selectall4","RESET"))
             ),br(),
             actionButton(style="background-color: #275c4d;color: #fff;width: 150px","","CDAT"),
             actionButton(style="background-color: #275c4d;color: #fff;width: 150px","","CDAT1"),

             fluidRow(
               column(style = "margin-top: 30px;font-weight: bold;line-height: 10px",6,"","Select Frequency"),
               column(6,
                      selectInput("analysis", label = "", 
                                  c("Monthly" = "all",
                                    "Yearly" = "specific"),
                                  selected = "all")

               )        ),br(),

                 fluidRow(
                   column(style = "font-weight: bold;line-height:     10px",6,"Select Scenerio",

                      selectInput(
                        "subsetType", "",
                        c("Monthly" = "all",
                          "Yearly" = "specific"),
                        selected = "all") 

               ),
               column(6,
                          div(style = "overflow-y:scroll;border: 1px solid     rgba(128, 128, 128, 0.52); max-height: 50px; min-height: 50px; background-    color:white; padding-left: 10px",

                              checkboxGroupInput('campaign5', '',
                                             HL_list,
                                                 selected = HL_list))

                   )        ),

                 fluidRow(
                   column(style = "font-weight: bold;line-height: 10px",6,
                          actionButton(style="background-color: #275c4d;text-    align:center;color: grey;width: 200px","selectall5","View Final Forecast")
               ),
                   column(6,
                          div(style = "font-weight: bold;line-height: 10px",
                              actionButton(style="background-color:     #275c4d;color: grey;width: 200px","selectall6","View Baseline Forecast")
                      )     )),


                 downloadButton("downloadData", "Download Data"),
                 #   checkboxGroupInput("checkGroup", label = h3("Goal"), 
                 #                     setNames(object = paste0("Manufacturer", 1:5), 
                 #                             nm = paste0("Manufacturer ",     1:5)),
                 #                   selected = "Manufacturer 1"),
                 selectInput(inputId = "dataset",
                             label = "Choose platform annotation file",
                             choices = c("cDat","pressure"))


    ),

    ##### Show data in Main Panel  
    # Show a plot of the generated distribution
    mainPanel(

      tabsetPanel(type = "tabs",
              tabPanel("Table", dataTableOutput('mytable1'),     dataTableOutput('mytable2')),
                  tabPanel("Plot", plotlyOutput("Conversionrate1"),
                           verbatimTextOutput("event")),
                  tabPanel("Editable Parameter", br(),actionButton("save",     "Save"), br(),
                           rHandsontableOutput("hot"))

      ))



  )
    )
shinyApp(ui = ui, server = server)
}

2 个答案:

答案 0 :(得分:0)

您可以将dplyr filter%in%运营商一起使用。

library(shiny)
library(ggplot2)
library(dplyr)

# Change rownames
cDat <- read.table(file.path(DATA_DIR, "DrugData.csv"), sep = ",",  header = 
                     TRUE, row.names = NULL)
campaigns_list <- unique(cDat$MANUFACTURER)
server <- function(input, output, session) {

  output$mytable1 <- renderDataTable({
    #cDat[input$campaign_list,]
    #print(input)
    cDat %>% filter(MANUFACTURER %in% input$campaign)
  })
}

ui <- fluidPage(

  # Application title
  titlePanel("Example"),
  # Sidebar with a slider input for the number of bins
  sidebarLayout(
    sidebarPanel(
      checkboxGroupInput('campaign', 'Manufacturer',
                         campaigns_list,
                         selected = campaigns_list)
    ),

    # Show a plot of the generated distribution
    mainPanel(
      dataTableOutput('mytable1'))
  )
)
shinyApp(ui = ui, server = server)

答案 1 :(得分:0)

使用包dplyr这很容易。只需像这样更改您的代码。

###############Assigning Packages
library(shiny)
library(ggplot2)
library(dplyr)
library(DT)

#############################
# Importing Data
cDat <- read.table(file = "data/DrugData.tsv", sep = ",",  header = 
                     TRUE, row.names = NULL)
############################

###### Preparing list for Checkbox & Change rownames
#campaigns_list <- unique(cDat$MANUFACTURER)

MANUFACTURER_list <- unique(cDat$MANUFACTURER)
DrugClass_list <- unique(cDat$DrugClass)
DrugType_list <- unique(cDat$DrugType)
columns <- names(cDat)
####################### Server.R##########
server <- function(input, output, session) {

  filteredData <- reactive({
    cDat %>% filter(MANUFACTURER %in% input$campaign &
                      DrugClass %in% input$campaign1 &
                      DrugType %in% input$campaign2 )
  })


  selectedData <- reactive({
    filteredData() %>% 
      select_(.dots = input$columns)
  })
  output$mytable1 <- renderDataTable({
    selectedData()
  })
}


####################### UI.R ##############
ui <- fluidPage(
  # Application title
  titlePanel("Example"),
  # Sidebar with a slider input for the number of bins
  sidebarLayout(
    sidebarPanel(
      checkboxGroupInput('campaign', 'Manufacturer',
                         MANUFACTURER_list,
                         selected = MANUFACTURER_list),
      checkboxGroupInput('campaign1', 'DrugClass',
                         DrugClass_list,
                         selected = DrugClass_list),
      checkboxGroupInput('campaign2', 'DrugType',
                         DrugType_list,
                         selected = DrugType_list),
      checkboxGroupInput('columns', 'Columns',
                         columns,
                         selected = columns)
    ),

    ##### Show data in Main Panel  
    # Show a plot of the generated distribution
    mainPanel(
      dataTableOutput('mytable1'))
  )
)
shinyApp(ui = ui, server = server)

希望这会有所帮助。