2017-02-11 3 views
1

私は、ユーザーが指定できるさまざまな入力に基づいて光沢のあるアプリケーションでデータフレームをサブセット化しています。入力フィールドが空の場合、サブセッティングは行われません。入力が空の場合、光沢のあるアプリでdata.frameをサブセット化しません。多くのif文なしでこれを行う方法は?

data_subset <- reactive({ 
    if (!is.null(input$input_a)) {data <- subset(data, a %in% input$input_a} 
    # lots of similar if statements for inputs b, c, d ... 
    data 
}) 

ここでは、入力がNULLかどうかを確認するこれらのifステートメントが多数あります。しかし、このような文が10個以上20個以下であると、コードは面倒で時間がかかるように見えます。

これを行うより良い方法はありますか?多分reqがここで助けることができますか?

答えて

2

必要に応じてこのコードを調整する必要があります。 inputは、サブセットに使用しているさまざまな要素を含むリストです。リアクティブ関数で必要なものを抽出し、高次関数Reduceを使用して、データをインデックスする論理ベクトルを思いつくことができます。

# Setup example 
input <- list(input_vs = NULL, input_am = 1, input_gear = 4) # Inputs coming from ui 
data <- mtcars # Data 


# In the reactive expression 
inpt <- reactiveValuesToList(input) 
indx <- inpt[grepl("input", names(inpt))] # Extract the inputs you want 
names(indx) <- gsub("input_", "", names(indx)) # Remove the prefix to get the associated variable names 

indx <- Filter(Negate(is.null), indx) # Remove the null ones 

# Find indices 
indx <- lapply(seq_along(indx), function(i) data[, names(indx)[i]] %in% indx[[i]]) 
indx <- Reduce(`&`, indx) 

# Subset data 
data[indx, ] 
+0

R6クラスであるので、シングルブラケットインデキシングは needRhelp

+0

関数 'reactiveValuesToListがありますそれは解決します。 – Raad

+0

ニース、ありがとう! indxがNULLでdata [indx、]が長さゼロのdata.frameであるため、すべての入力がNULLの場合は動作しません – needRhelp

1

私は単純なforループを使用して解決策を考え出しました。私は、入力が空であるかどうかをチェックするヘルパー関数を定義し、入力が空でない場合にのみサブセットを定義しました。光沢のある入力で

library(shiny) 

data <- iris 

# return TRUE if shiny input is empty, e.g. NULL, "", FALSE 
is_input_empty <- function(ui_input) { 
    if (is.null(ui_input)) return(TRUE) 
    if (length(ui_input) != 1) return(FALSE) 
    if (ui_input == "") return(TRUE) 
    if (ui_input == FALSE) return(TRUE) 
    return(FALSE) 
} 

ui <- fluidPage(
    selectizeInput("Species", "Species", choices = levels(data$Species), 
       multiple = TRUE, selected = c("versicolor", "setosa")), 
    plotOutput("plot_iris") 
) 

server <- function(input, output) { 

    data_subset <- reactive({ 
     input_vars <- "Species" 

     # iterate over the inputs, if not NULL subset the data 
     for (i in input_vars){ 
     if (!is_input_empty(input[[i]])) {data <- data[data[, i] %in% input[[i]], ]} 
     } 
     data 
    }) 

    output$plot_iris <- renderPlot(plot(data_subset()$Sepal.Length, 
             data_subset()$Sepal.Width)) 
} 

shinyApp(ui, server) 
関連する問題