【问题标题】:R - dplyr - ifelse and filterR - dplyr - ifelse 和过滤器
【发布时间】:2016-06-28 23:10:11
【问题描述】:

我正在 Shiny 上构建一个小部件,我希望有“全部”选项来选择所有可用数据,并且不执行过滤。

基本上,我想要以下代码(使用 dplyr):

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

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

它将根据 filt 的值过滤 mtcars

如果 filt=="All" 那么它不会过滤并简单地返回 mtcars

任何优雅的解决方案?

【问题讨论】:

  • if (filt == 'All') {data1 &lt;- mtcars} else {data1 &lt;- filter(mtcars, carb == filt)} 怎么样?
  • 是的,我想过——但是如何将它嵌入到 Shiny 的反应函数中呢?我尝试了以下解决方案,但它不起作用:if (filt == 'All') {data1 &lt;- reactive({mtcars }) } else {data1 &lt;-reactive({filter(mtcars, carb == filt) })}
  • 在响应式末尾添加data。它将返回该数据框。

标签: r filter widget shiny dplyr


【解决方案1】:

这是我的尝试。如果folt="All" 则没有过滤器,否则只返回带有carb==filt 的汽车。

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

应该做的伎俩

【讨论】:

    【解决方案2】:

    这样的事情应该可以工作(通过适当的修改以在此反应中使用 filt 变量的输入值):

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

    【讨论】:

    • 工作得很好!非常感谢 Gopola。
    猜你喜欢
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 2018-11-11
    • 1970-01-01
    相关资源
    最近更新 更多