使用 r markdown 的闪亮应用程序的反应函数中的 dplyr

dplry in reactive function for shiny app using rmarkdown

我正在尝试结合以下两个问题的答案:

在第一个问题中,我看到了如何在 shiny / rmarkdown 中正确使用 reactive to subset。我第二次向我展示了如何使用 dplry 来汇总我的数据以计算 % 收益率。现在我正在尝试将 dplry 与反应函数一起使用,以便我的 % yield 可以受到用户输入的影响。我快到了,但收到 "unused argument" 错误,然后是数字列表。这是一个例子:

---
title: "Yield5"
author: "P Downs"
date: "Tuesday, May 26, 2015"
output: html_document
runtime: shiny
---

# Create user input for reactive subsetting
```{r echo=FALSE}
sliderInput("Meas_L", label = "Measure lower bound:",
            min=2, max=9, value=3, step=0.1)

sliderInput("Meas_U", label = "Measure upper bound:",
            min=2, max=9, value=8, step=0.1)

# create reactive variables for use in subsetting below

ML <- reactive({input$Meas_L})
MU <- reactive({input$Meas_U})

```

# Create example data frame. Measurement is grouped by batch and ID number
```{r echo=FALSE, message=FALSE}

library(plyr)
library(ggplot2)
library(dplyr)


set.seed(10)
Measurement <- rnorm(1000, 5, 2)
ID <- rep(c(1:100), each=10)
Batch <- rep(c(1:10), each=100)

df <- data.frame(Batch, ID, Measurement)

df$ID <- factor(df$ID)
df$Batch <- factor(df$Batch)

# function used to count number of "passed" data based on user input from sliders i.e. how many data points are between ML and MU

countFunc <- reactive({ function(x) sum( (x > ML()) & (x < MU()) )})

# user dplyr to produce summary of count for: total data, passed data, then calculate % yield 

totals <- reactive({
  df %>% group_by(Batch, ID) %>%
  summarize(total = length(Measurement), x = countFunc(Measurement)) %>%
  mutate(Yield = (x/total)*100) %>%
  as.data.frame()
  })

# Plot yield by against ID number grouped by batch

renderPlot({ggplot(totals(), aes(ID, Yield, colour=Batch)) + geom_point() +
              scale_y_continuous(limits=c(0,100))})

我不明白为什么函数中有一个未使用的参数?我最终想将函数扩展到更多的一个变量,但我会把它留到另一天!

A reactive 不是函数,您不能将参数传递给 reactive。您的函数 countFunc 应该是 function,而不是 reactive。然后使用适当的(反应性)值调用该函数。

countFunc <- function(x, ml, mu) sum( (x > ml) & (x < mu) )

totals <- reactive({
  df %>% group_by(Batch, ID) %>%
  summarize(total = length(Measurement), x = countFunc(Measurement, ML(), MU())) %>%
  mutate(Yield = (x/total)*100) %>%
  as.data.frame()
  })