如何为dplyr :: summarize()制作Shiny的输入$ var consumable

时间:2017-04-16 11:47:42

标签: r shiny dplyr markdown

我有以下 Rmarkdown Shiny

---
title: "My Title"
runtime: shiny
output: 
  flexdashboard::flex_dashboard:
    vertical_layout: scroll
    theme:  bootstrap
    orientation: rows
---

```{r setup, include=FALSE}
library(flexdashboard)
```

Rows {data-height=700}
-----------------------------------------------------------------------

### Mate-pair Mapping Distribution

```{r mate_pair_distribution, echo=FALSE}
library(ggplot2)
library(tidyverse)
sidebarPanel(
  selectInput("col_id", label = "Features",
              choices = c("carat", "depth","price"), selected = "price"),
  selectInput("op_id", label = "Quality:",
              choices = c("All", "Ideal","Premium","Good","Very Good"), selected = "Good"),

  sliderInput("n_breaks", label = "Number of bins:",
               min = 20, max = 50, value = 30, step = 1)
)


#renderText(input$op_id)

mainPanel(
  renderPlot({
    # Prepare for the data
    dat  <- diamonds %>% filter(cut == input$op_id)
    if(input$op_id == "All") {
      dat <- diamonds
    }

    # Plotting 
    ggplot(dat, aes(dat %>% select(.,contains(input$col_id)))) +
    ggtitle(input$op_id, subtitle = input$col_id) +
    geom_histogram(bins = input$n_breaks) +
    scale_x_continuous() +
    xlab(input$col_id) +
    theme_light()

  }, height=400, width=400),
  br(),
  br(),
  renderPrint({
    dat  <- diamonds %>% filter(cut == input$op_id)
    if(input$op_id == "All") {
      dat <- diamonds
    }

   dat %>% 
      select(.,contains(input$col_id)) %>%
      summarise(mean = mean(input$col_id), sd=sd(input$col_id), n=n())
  })
)

```

产生此输出

enter image description here

您可以在renderText()NA值中看到mean展示sd。 它是由这条线引起的

 dat %>% 
          select(.,contains(input$col_id)) %>%
          summarise(mean = mean(input$col_id), sd=sd(input$col_id), n=n())

那么如何为input$col_id制作summarise()耗材呢? 什么是正确的方法?

非闪亮上下文的结果是:

> diamonds %>% filter(cut=="Good") %>% select(price)  %>% summarise(mean = mean(price), sd=sd(price), n=n())
# A tibble: 1 × 3
      mean      sd     n
     <dbl>   <dbl> <int>
1 3928.864 3681.59  4906

1 个答案:

答案 0 :(得分:3)

使用dplyr v0.5.0.9002 )的开发版本,您可以使用rlang::sym()将字符串转换为符号,然后使用非引号运算符({{ 1}}或!!)来引用dplyr动词中的变量。

UQ

给出了:

library(dplyr)

var1 <- "Good" # replace with input$op_id
var2 <- rlang::sym("price") # replace with input$col_id

diamonds %>%
  filter(cut == var1) %>%
  select_at(vars(!!var2)) %>%
  summarise_at(vars(!!var2), funs(mean, sd, n()))

如果您有多个变量,请将## A tibble: 1 × 3 # mean sd n # <dbl> <dbl> <int> #1 3928.864 3681.59 4906 与非引用拼接运算符(rlang::syms()!!!)一起使用。例如:

UQS

给出了:

var1 <- "Good" 
var2 <- rlang::syms(c("price", "depth")) 

diamonds %>%
  filter(cut == var1) %>%
  select_at(vars(UQS(var2))) %>%
  summarise_at(vars(UQS(var2)), funs(mean, sd, n()))

有关详细信息,请查看quasiquotation section小插图的Programming with dplyr