ddply 中用于 rmarkdown shiny 的反应性子集

Reactive subset in ddply for rmarkdown shiny

我正在尝试根据用户可定义的输入计算和绘制某些数据的产量百分比。我正在使用 rmarkdown 和 shiny 来做到这一点。当通过 ddply 传递反应性子集以计算子集中的行数时,我一直卡住.."invalid (null) left side of assignment".

这是一个示例数据集:

---
title: "Yield3"
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}

library(plyr)
library(ggplot2)

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)

# reactive subset of data based on user input of sliders 

pass <- reactive({subset(df, Measurement > ML() & Measurement < MU())})

# Count number of rows in complete data set

ac <- ddply(df, c("Batch", "ID"), function(x) nrow(x))
colnames(ac) <- c("Batch", "ID", "Total")

# Count number of row in passed data set (reactive because inputs are     reactive)

bc <- reactive({ddply(pass(), c("Batch", "ID"), function(x) nrow(x))})
colnames(bc()) <- c("Batch", "ID", "Pass")

# Calculate yield by dividing passed by total rows (also reactive)

bc()$Yield <- (bc()$Pass / ac$Total) * 100

# Plot yield by against ID number grouped by batch

renderPlot({ggplot(bc(), aes(ID, Yield, colour=Batch)) + geom_point()})

我读过我认为所有其他问题都基于 shiny 中的反应性子集。我认为这是最接近的 (R Shiny reactive subset data - ERROR object of type 'closure' is not subsettable) but I still cant put 2 and 2 together and its driving me crazy. Also I have read this (Error in <my code> : target of assignment expands to non-language object),这表明我正在为一个不存在但我看不到的变量赋值。请有人指出我的明显错误,或者甚至可能是更优雅的计算收益率的方法。非常感谢

首先,您试图在反应式表达式之外修改反应式对象。我建议在表达式中定义列名。

其次,我不认为修改bc()$Yield是授权操作。所以我会尝试在反应式表达式中生成 Yield

下面是一段经过编辑的代码。它生成一个没有错误的输出。您可能需要稍微调整一下。 (我认为 bcbc2 可以合并)。

# Count number of row in passed data set (reactive because inputs are reactive)
bc <- reactive({
  a<-ddply(pass(), c("Batch", "ID"), function(x) nrow(x))
  colnames(a) <- c("Batch", "ID", "Pass")
  return(a)
  })

# Calculate yield by dividing passed by total rows (also reactive)
bc2 <- reactive({
  a<-(bc()$Pass / ac$Total) * 100
  a<-cbind(a,bc())
  colnames(a)<- c("Yield","Batch", "ID", "Pass")
  return(a)
 })

# Plot yield by against ID number grouped by batch
renderPlot({ggplot(bc2(), aes(ID, Yield)) + geom_point()})