R Shiny - 输出摘要统计信息

8
我刚开始接触R和R Shiny。我尝试了一些教程并构建了一个非常简单的数据探索应用程序——您选择两个变量,它会给出一个箱线图。
我添加了Rmarkdown功能,以便用户可以下载其结果的PDF文件,但希望包括一些汇总统计信息。例如,他们选择年龄和性别作为变量,PDF打印年龄、性别的摘要以及生成的箱线图。
我只是无法打印摘要。我尝试了几种方法——如果我只是summary(input$variable),它只会给出空白详细信息。我添加了代码来存储input$variable选择通过server.r并尝试了该对象的摘要,但该对象无法找到。我已经在谷歌上搜索答案大约两天了,但我放弃了!如果有人能帮助我,这将非常有益,我认为我不熟悉R,无法弄清楚我错在哪里。
对于我初学者的R知识,我很抱歉,我相信这应该不会引起问题。
一些相关代码片段——还要注意的是,我尝试使其工作的一些代码我知道是错误的方式,但我尝试了许多不同的方式,我想我会粘贴最后一次尝试以获得某些内容的出现。 ui.R
#input
sidebarPanel
(
selectInput("dataset","Data:", 
            list(age = "ageData")
),
uiOutput("variable"),   # depends on dataset ( set by output$variable in  server.R)
uiOutput("group"),          # depends on dataset    ( set by output$group in  server.R)
selectInput("plot.type","Plot Type:", 
            list(Boxplot = "Boxplot", Histogram = "Histogram", Density = "Density", Bar        = "Bar")
),
checkboxInput("show.points", "Show points", TRUE),
checkboxInput("outliers", "Show outliers", TRUE),
br(),

helpText("Click download to output your plot and variable details to a document."),
radioButtons('format', 'Document format', c('PDF', 'HTML', 'Word'),
             inline = TRUE),
downloadButton('downloadReport'),
br(),
br(),
img(src = "logo.jpg")
  ),


   # checkboxInput("outliers", "Show outliers", FALSE)
  #),   

  # output              
  mainPanel(
    h3(textOutput("caption")),
    #h3(htmlOutput("caption")),
    uiOutput("plot") # depends on input 
  )
))

server.R

# shiny server side code for each call
shinyServer(function(input, output, session){
  #update variable and group based on dataset
  output$variable <- renderUI({ 
    obj<-switch(input$dataset,
                "ageData" = ageData)     
    var.opts<-namel(colnames(obj))
    selectInput("variable","y-axis:", var.opts) # uddate UI                  
  }) 

  output$group <- renderUI({ 
    obj<-switch(input$dataset,
                "ageData" = ageData)     
    var.opts<-namel(colnames(obj))
    selectInput("group","x-axis:", var.opts) # uddate UI                 
  }) 

  output$caption<-renderText({
    switch(input$plot.type,
           "Boxplot"    =   "Boxplot",
           "Histogram" =    "Histogram",
           "Density"    =   "Density plot",
           "Bar"        =   "Bar graph")
  })

  regFormula <- reactive({
    as.formula(paste(input$group, data=ageData))
  })

  output$regPrint <- renderPrint({
  summary(regFormula(), data = ageData)
  })

  output$plot <- renderUI({
    plotOutput("p")
  })

  #plotting function using ggplot2
  output$p <- renderPlot({

plot.obj<<-list() # not sure why input$X can not be used directly?
plot.obj$data<<-get(input$dataset) 
plot.obj$variable<<-with(plot.obj$data,get(input$variable)) 
plot.obj$group<<-with(plot.obj$data,get(input$group)) 

#dynamic plotting options
if(input$outliers==FALSE) {
plot.type<-switch(input$plot.type,
                  "Boxplot"     =   geom_boxplot(outlier.size=0),
                  "Histogram" = geom_histogram(alpha=0.5,position="identity"),
                  "Density"     =   geom_density(alpha=.75),
                  "Bar"         =   geom_bar(position="dodge")
)
}
else 
  {
    plot.type<-switch(input$plot.type,
                      "Boxplot"   =     geom_boxplot(),

                      "Histogram" = geom_histogram(alpha=0.5,position="identity"),
                      "Density"     =   geom_density(alpha=.75),
                      "Bar"         =   geom_bar(position="dodge")
    )
  }
require(ggplot2)
#plotting theme
    .theme<- theme(
      axis.line = element_line(colour = 'gray', size = .75), 
  panel.background = element_blank(),  
  plot.background = element_blank()
)    
if(input$plot.type=="Boxplot")  {       #control for 1D or 2D graphs 
  p<-ggplot(plot.obj$data, 
            aes(
              x         = plot.obj$group, 
              y         = plot.obj$variable,
             fill   = as.factor(plot.obj$group))

  ) + plot.type

  if(input$show.points==TRUE)
  { 
    p<-p+ geom_point(color='black',alpha=0.5, position = 'jitter')
  }

} else {

  p<-ggplot(plot.obj$data, 
            aes(
              x         = plot.obj$variable,
              fill  = as.factor(plot.obj$group),
              group     = as.factor(plot.obj$group),
              color     = as.factor(plot.obj$group)
            )
  ) + plot.type
}

p<-p+labs(
  fill  = input$group,
  x         = "",
  y         = input$variable
)  +
  .theme
print(p)


   })   

  output$downloadReport <- downloadHandler(
    filename = function() {
      paste('my-report', sep = '.', switch(
        input$format, PDF = 'pdf', HTML = 'html', Word = 'docx'
      ))
    },

    content = function(file) {
      src <- normalizePath('report.Rmd')

  # temporarily switch to the temp dir, in case you do not have write
  # permission to the current working directory
  file.copy(src, 'report.Rmd')

  library(rmarkdown)
  out <- render('report.Rmd', switch(
    input$format,
    PDF = pdf_document(), HTML = html_document(), Word = word_document()
  ))
  file.rename(out, file)
}
  )

})

**report.Rmd**

Here are some summary statistics:

```{r summary}


print(regFormula())

summary(regFormula(), data=ageData)




```

ageData是什么?请提供一个最小可重现的示例。 - jdharrison
嗨,ageData只是一个测试数据集,变量和信息很少 -

年龄 性别 婚姻状况

1 23 男性 单身

2 29 女性 已婚

3 43 男性 已婚

未来需要改进,但主要是尝试让它能够在我选择图表的变量为年龄时,点击“下载报告”并告诉我样本中年龄的平均数、中位数、标准差等。我知道它不适用于其他变量。
- user3265881
1个回答

9

在服务器端,将您的总结语句包含在renderPrint({})中即可解决问题,并使用verbatimTextOutput()用于用户界面! 在此链接的第4步中可以看到示例:

这是您应用程序的代码,让我们逐步执行创建过程。我们已经定义了标题面板。现在,我们将在侧边栏面板中定义一些小部件。

ui.R

shinyUI(fluidPage(
    titlePanel("My first Shiny app!"),
  sidebarLayout(
    sidebarPanel(
    selectInput("var",label="Choose a variable",choice=c("Sepal.Length"=1,
                                                                  "Sepal.Width"=2,
                                                                  "Petal.Length"=3,
                                                                  "Petal.Width"=4), selectize=FALSE)),
    mainPanel(
      h2("Summary of the variable"),
      verbatimTextOutput("sum"),
      plotOutput("box")
      )
    ))
  )

server.R

library(shiny)
library(datasets)

shinyServer(function(input,output){

output$sum <- renderPrint({

  summary(iris[,as.numeric(input$var)])
  })

output$box <- renderPlot({

  x<-summary(iris[,as.numeric(input$var)])
  boxplot(x,col="sky blue",border="purple",main=names(iris[as.numeric(input$var)]))
})
}
)

我们使用的数据来自于R中已经存在的数据集库。您可以通过调用library(datasets)函数来访问此数据集。在这里,我们使用了鸢尾花(iris)数据集。您可以通过在R控制台中调用?iris函数来了解有关鸢尾花数据集的信息。

http://sanaitics.com/UploadedFiles/html_files/8737Shiny_article.html.

verbatimTextOutput("regPrint")将达到所需效果。


虽然这个链接可能回答了问题,但最好在此处包含答案的基本部分并提供参考链接。如果链接页面更改,仅有链接的答案可能会失效。- 来自审查 - Stephan Vierkant
谢谢。我会编辑我的答案。在那之后,您是否可以 kindly 删除您提供的向下箭头。它会阻止我回答未来的问题并建立我的“声望”积分。 - Ben Robinson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接