显示文字和数据R降价闪亮

时间:2017-03-16 17:44:08

标签: r shiny

昨天我尝试用R studio编写我的第一个交互式降价文档,最后它工作正常,但我无法弄清楚如何访问渲染图()中的数据。这可能很容易,但我找不到合适的例子。可能是某种灵魂会帮助我吗?

我试图用这段代码来说明中心极限定理

---
title: "Eksperimentering med utvalg"
author: "Per G. Østerlie"
date: "15 3 2017"
output: html_document
runtime: shiny
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```


# CLT


```{r}
fisk_masse =sample(1:1000,500,replace=TRUE)

```
```{r histogram, echo=FALSE}
hist(fisk_masse, 
     main="Masse i populasjon", 
     xlab="Masse", 
     ylab="Antall",
     border="darkgray", 
     col="lightgray",
     xlim=c(0,1000),
     las=1, 
     breaks=10)
```

```{r, echo=FALSE}
paste("Gjennomsnitt: ",mean(fisk_masse))
paste("Standardavvik: ",sd(fisk_masse))
```

# Sample

50 fish, choose number of samples

```{r, echo=FALSE}
inputPanel(
  sliderInput("n_utvalg", label = "Antall utvalg",
              min = 50, max = 800, value = 100, step = 50)
)
renderPlot({
xbar = rep(0,input$n_utvalg)
for (i in 1:input$n_utvalg){xbar[i]=mean(sample(fisk_masse,50,replace=FALSE))}
hist(xbar, 
     main="Gjennomsnittsmasse i stikkprovene", 
     xlab="Masse", 
     ylab="Antall",
     border="darkgray", 
     col="lightgray",
     #xlim=c(0,1000),
     las=1, 
     breaks=10)

m <-mean(xbar)
std<-sqrt(var(xbar))

})

现在我想显示变量m(或mean(xbar)和std。我希望它们显示在直方图下。我的所有尝试最终都会显示一条消息,即xbar未知(这有意义)谁能指导我回答?

1 个答案:

答案 0 :(得分:2)

在Shiny中,您必须渲染文本,与输入动态时渲染绘图的方式类似。除了renderPlot()之外,您还必须在最后一个块中添加renderText()部分。

我建议在所谓的无效导体中计算xbar。在无功导体的帮助下,您只需为绘图和文本输出计算一次xbar

您可以使用此工作示例替换上一个块:

```{r, echo=FALSE}

    inputPanel(
      sliderInput("n_utvalg", label = "Antall utvalg",
                  min = 50, max = 800, value = 100, step = 50)
    ) 
  computeXbar <- reactive({
    xbar = rep(0,input$n_utvalg)
    for (i in 1:input$n_utvalg){xbar[i]=mean(sample(fisk_masse,50,replace=FALSE))}
    xbar
  })

  renderPlot({
    xbar <- computeXbar()
    hist(xbar,
         main="Gjennomsnittsmasse i stikkprovene",
         xlab="Masse",
         ylab="Antall",
         border="darkgray",
         col="lightgray",
         #xlim=c(0,1000),
         las=1,
         breaks=10)

    })

  renderText({
    xbar <- computeXbar()
    paste(
      "The mean is: ", mean(xbar), " and the standard deviation is ", sqrt(var(xbar))
    )
  })

```

您可以在此概述文章中找到有关闪亮反应性的更多信息:https://shiny.rstudio.com/articles/reactivity-overview.html