【问题标题】:Subsetting and whole dataset shiny R子集和整个数据集闪亮的 R
【发布时间】:2021-07-08 19:43:17
【问题描述】:

我正在使用 Shiny 并且想仅使用某个子集和整个数据集来绘制一些东西。 用户可以使用 selectInput 选择是绘制整个数据集还是仅绘制一个子集。

到目前为止,我有这个:

ui <- fluidPage(
selectInput(inputId = "select", label = "Choose subset of analysis", choices = levels(df$c), selected = "groupA"),
  verbatimTextOutput("summary")
)

server <- ({
datasetInput <- reactive({
    req(input$select)
    a <- subset(df, Haircolor %>% in levels(df$c))
    return(a)
  })

output$summary<- summary(datasetInput)
})

对 df$c 的不同级别进行子集化可行,但如果不想进行子集化,但在分析中包含所有观察值,我该怎么办?

非常感谢。

【问题讨论】:

  • 能否提供dput(df)方便测试?

标签: r dataframe dplyr shiny


【解决方案1】:

我认为您的代码有几个问题。由于我们不知道原始数据,我展示了一个带有 iris 数据集的示例。它应该很容易适应您的问题。

library(shiny)
library(dplyr)

myiris <- mutate(iris, Species = as.factor(Species))

shinyApp(
  ui = fluidPage(
      selectInput(inputId = "select",
                  label = "Choose subset of analysis",
                  choices = c("all", levels(myiris$Species)),
                  selected = "all"),
      verbatimTextOutput("summary")
    ),
  
    server = function(input, output) {
    
    datasetInput <- reactive({
    req(input$select)
    filter(myiris, input$select == "all" | Species == input$select)
    # alternatively `subset` works as well:
    # subset(myiris, input$select == "all" | Species == input$select)
    })

    output$summary <- renderText(summary(datasetInput()))
  })

为什么filter(myiris, input$select == "all" | Species == input$select) 有效?

filtersubset 将表达式作为第二个参数。重要的是

  1. 这可以是任何逻辑表达式。表达式不一定需要引用列名。
  2. 如果表达式与data.frame 的行数不匹配,则表达式将被重新循环。注意subsetfilter 有不同的回收规则。但是,两者都会将length == 1 的表达式循环到data.frame 的行数。
  3. 表达式可能包含布尔运算符(&amp;| 等)

考虑到这一点,我们可以构造表达式: input$select == "all" | Species == input$select

由于input$select == "all" 属于length == 1,它将被回收以匹配Species == input$select 中的元素数,即data.frame 的行数。

由于我们使用A或Operator |,因此在选择all时,表达式将在TRUE 987654339 @。如果未选择all,则表达式Species == input$select 将为与所选input$select 匹配的所有行的TRUE

【讨论】:

  • 非常感谢,这成功了!您能帮我理解代码:r如何知道选择“全部”时如何结合所有级别?过滤器是如何工作的?
  • @Phil.He:我加了解释!
【解决方案2】:

试试这个

ui <- fluidPage(
  selectInput(inputId = "select", label = "Choose subset of analysis", choices = c("All", unique(df$c)), selected = "groupA"),
  uiOutput("summary")
)

server <- ({
  datasetInput <- reactive({
    req(input$select)
    if (input$select=="All") { a <- df
    }else a <- subset(df, Haircolor %in% input$select)
    return(a)
  })
  
  output$summary<- renderUI({summary(datasetInput())})
})

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-18
相关资源
最近更新 更多