R Shiny -输出汇总统计数据



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

我添加了markdown功能,以便用户可以下载他们的结果的PDF,但希望包括一些汇总统计数据。例如,他们选择年龄和性别作为变量,PDF打印年龄、性别的摘要以及生成的箱线图。

我就是不能打印摘要。我已经尝试了几个方法-如果我只是总结(输入$variable)它只是给出空白的细节。我已经添加了通过服务器存储输入$变量选择的代码。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 
  )
))

服务器。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)


```

renderPrint({})与您的摘要语句包装在里面是你的问题的答案这里在服务器端与veratimtextoutput()一起为ui端!参见本链接的步骤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(datassets)函数来访问该数据集。我们在这里使用了虹膜数据集。您可以通过在R控制台中调用?iris函数来了解iris数据集。

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

veratimtextoutput ("regPrint")就可以了

最新更新