【问题标题】:R Shiny - Output summary statisticsR Shiny - 输出汇总统计
【发布时间】:2014-07-11 15:54:37
【问题描述】:

我刚刚开始使用 R 和 R Shiny。我一直在玩一些教程并构建了一个非常简单的数据探索应用程序 - 你选择两个变量,它会给你一个箱线图。

我添加了 Rmarkdown 功能,以便用户可以下载其结果的 PDF,但希望包含一些摘要统计信息。示例 - 他们选择年龄和性别作为变量,PDF 打印年龄、性别的摘要以及生成的箱线图。

我只是无法打印摘要。我尝试了几种方法 - 如果我只是 summary(input$variable) 它只会给出空白细节。我已经添加了通过 server.r 存储 input$variable 选择的代码,并尝试了它的摘要,但无法再找到该对象。我已经在谷歌上搜索了大约两天的答案,但我放弃了!如果有人可以帮助我,这将非常有益,我认为我对 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。请提供一个可重现的最小示例。
  • 嗨,ageData 只是一个测试数据集,变量和信息最少 - ## Age Gender Marital Status ## 1 23 Male Single ## 2 29 Female Married ## 3 43 Male Married 有待改进将来,但目前主要尝试使用它,以便我可以点击“下载报告”,如果这是为图表选择的变量,它会告诉我样本中年龄的平均中位数 sd 等。我知道它不适用于其他变量。

标签: r shiny


【解决方案1】:

renderPrint({}) 将您的摘要语句包含在其中,这是您在服务器端的问题的答案,以及用于 ui 端的 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")
      )
    ))
  )

服务器.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 函数来了解 iris 数据集。

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

verbatimTextOutput("regPrint") 可以解决问题。

【讨论】:

  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
  • 谢谢。我将编辑我的答案。在我这样做之后,请您删除您提供的向下箭头。它阻止我回答未来的问题并建立我的“声誉”点。
猜你喜欢
  • 2021-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多