ddply中的反应子集用于rmarkdown闪亮

时间:2015-05-26 10:02:55

标签: r shiny subset r-markdown

我正在尝试根据用户可定义的输入计算并绘制一些数据的%收益率。我正在使用rmarkdown和闪亮来做这件事。当通过ddply传递一个反应子集来计算子集中的行数时,我一直卡住了。“无效(null)赋值的左侧”。

以下是一个示例数据集:

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

我已经阅读了我认为所有其他问题都基于反应性子集的闪亮。我认为这是最接近的(R Shiny reactive subset data - ERROR object of type 'closure' is not subsettable),但我仍然不能把2和2放在一起,它让我疯狂。我也读过这个(Error in <my code> : target of assignment expands to non-language object),这表明我正在为一个不存在的变量赋值,但我看不到它。请有人指出我的明显错误,甚至可能是一种更优雅的方式来计算收益率。非常感谢

1 个答案:

答案 0 :(得分:2)

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

其次,我不认为修改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()})