dplry在反应函数中使用rmarkdown进行闪亮的应用程序

时间:2015-05-27 09:12:57

标签: r shiny dplyr

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

Reactive subset in ddply for rmarkdown shiny

Maintain data frame rows after subet

在第一个问题中,我展示了如何在闪亮/ rmarkdown中正确使用反应子集。我第二次向我展示了如何使用dplry汇总我的数据以计算%收益率。现在我尝试使用带有反应函数的dplry,这样我的%yield就会受到用户输入的影响。我几乎在那里,但得到一个错误的“未使用的参数”然后是一个数字列表。这是一个例子:

---
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))})

我无法理解为什么函数中有一个未使用的参数?我最终想要将函数扩展到更多的一个变量,但我将保存另一天!

1 个答案:

答案 0 :(得分:2)

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()
  })