R - dplyr - ifelse and filter

2020-05-06 08:18发布

I am building a widget on Shiny, and I would like to have the option "all" to select all of the data available, and don't perform a filtering.

Basically, I would like to have the following code (using dplyr):

filt<-sample(c("All", unique(mtcars$carb)),1)

data1<- mtcars %>% 
                  ifelse (filt=="All", select(), filter(carb==filt))

It will filter mtcars based on the value of filt.

If filt=="All" then it does not filter and return simply mtcars.

Any elegant solution?

2条回答
Explosion°爆炸
2楼-- · 2020-05-06 08:50

Here is my try. If folt="All" then there is no filter, otherwhise just the Cars with carb==filt is returned.

   filt <-sample(c("All", unique(mtcars$carb)),1)
    filt
    if(filt=="All"){
      data1<- mtcars
    } else {
      data1<- filter(mtcars, mtcars$carb==filt)
    }

should do the trick

查看更多
混吃等死
3楼-- · 2020-05-06 09:02

Something like this should work (with proper modifications to use the input value in this reactive for the filt variable):

reactiveObject <- reactive({
  filt <- sample(c("All", unique(mtcars$carb)),1)

  if (filt == 'All') {
    data1 <- mtcars
  } else {
    data1 <- filter(mtcars, carb == filt)
  }
  data1
})
查看更多
登录 后发表回答