2017-11-07 1 views
0

이것은 출력이 data.frame 인 iris 인 반짝 이는 응용 프로그램입니다. 행은 확인란으로 필터링 할 수 있습니다. 나는 내 코드가 다소 지저분하고 복잡하다고 생각한다.
누구나 간단하게, 바보로 유지하는 방법을 알고 있습니까?checkboxGroupInput에 의한 데이터 프레임의 행 필터링

library(shiny) 

# ui ########################################################################### 
ui <- fluidPage(
    checkboxGroupInput("filterSpecies", "filterSpecies", 
        selected = c("setosa", "Sepal.WidthBiggerThen3"), 
        c("setosa", "Sepal.WidthBiggerThen3") 
), 
    tableOutput("table") 
) 


# global ####################################################################### 
load(iris) 

filter <- function(dt, vars){ 
    # only if there is min 1 no NA element 
    if(any(!is.na(vars))){ 
    vars <- unlist(strsplit(vars, "\\s+")) 
    } 

    # value of checkbox 
    var1exist <- "setosa" %in% vars 
    var2exist <- "Sepal.WidthBiggerThen3" %in% vars 

    cond1 <- dt$Species == "setosa" 
    cond2 <- dt$Sepal.Width > 3 

    # negate if the checkbox is false 
    if(var1exist){ 
    cond1 <- T 
    }else{ 
    cond1 <- !cond1 
    } 

    if(var2exist){ 
    cond2 <- T 
    }else{ 
    cond2 <- !cond2 
    } 

    condition <- cond1 & cond2 
    dt[condition, ] 
} 


# server ####################################################################### 
server <- function(input, output){ 

    values <- reactiveValues(x = iris) 

    output$table <- renderTable({(values$x)}) 

    # filtering 
    observe({ 
    values$x <- filter(iris, input$filterSpecies) 
    }) 
} 


shinyApp(ui, server) 

답변

1

reactValues를 사용하는 대신에 반응성 기능을 사용하여 시도하는 것보다 복잡해야합니다.

그리고 당신이의 두 경우 모두에 값을 asigning 경우 한 Statment는 asignment의 경우 한 Statment 퍼팅하려고하면

library(shiny) 

# ui ########################################################################### 
ui <- fluidPage(
    checkboxGroupInput("filterSpecies", "filterSpecies", 
        selected = c("setosa", "Sepal.WidthBiggerThen3"), 
        c("setosa", "Sepal.WidthBiggerThen3") 
), 
    tableOutput("table") 
) 


# global ####################################################################### 
load(iris) 



# server ####################################################################### 
server <- function(input, output){ 
    filter <- reactive({ 
    # only if there is min 1 no NA element 
    dt = values() 
    vars = input$filterSpecies 



    # negate if the checkbox is false 
    cond1 <- if("setosa" %in% vars){ 
     dt$Species == "setosa" 
    }else{ 
     dt$Species != "setosa" 
    } 

    cond2 <- if("Sepal.WidthBiggerThen3" %in% vars){ 
     dt$Sepal.Width > 3 
    }else{ 
     dt$Sepal.Width <= 3 
    } 
    condition <- cond1 & cond2 
    dt[condition, ] 
    }) 

    values <- reactive({iris}) 

    output$table <- renderTable({filter()}) 

    # filtering 

} 


shinyApp(ui, server) 
관련 문제