samedi 24 août 2019

Define a dataframe based on an if statement in R

I am creating a web app using R shiny. I want the data that is used to populate a datatable to react to a user-input filter.

In this case, the filter is a fuel type - diesel or spirit. The user can choose one or the other or both. The options are "Diesel", "Spirit" or "All". If the user chooses "Diesel" or "Spirit", then it is easy as you just filter the underlying data by Fuel_Type (#the name of the column) == input$fuel (#the ID of the user input). But of course if the user chooses "All", then we don't want the data to be filtered at all.

Therefore I have attempted to use an if_else statement like this

data <- if_else(input$fuel == "All", data, filter(data, Fuel_Type == input$fuel)

I get the following error:

Error: Can't use numeric NA as column index with [

My understanding is that if_else doesn't work with defining a dataframe based on a conditional. So I would like to know how to do this.

Aucun commentaire:

Enregistrer un commentaire