Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R Shiny - Output summary statistics

Tags:

r

shiny

I've just started working with R and R Shiny. I've been playing around with some of the tutorials and built a very simple data exploring application - you pick two variables, it gives you a boxplot.

I added in the Rmarkdown features so the user can download a PDF of their results but was hoping to include some summary statistics. Example - they pick age and gender as their variables, the PDF prints the summary of age, gender and also the boxplot that was generated.

I just cannot get the summary to print. I've tried a couple of methods - if I just summary(input$variable) it just gives blank details. I've added in code that stores the input$variable choice through server.r and tried a summary of that also but the object can no longer be found. I've been googling for answers for about two days now but I give up! If anyone could help me this would be greatly beneficial, I think I'm just not familiar enough with R to figure out where I'm going wrong.

Apologies for my beginner knowledge of R, I'm sure this is one of those things that shouldn't really be causing problems.

Some extracts of the relevant code - Also, just to note, some of the code there of me attempting to get it to work I know is the wrong way to go about it just I'd tried so many different ways I figured I'd paste the last attempt to get something to appear.

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)




```
like image 994
user3265881 Avatar asked Jul 11 '14 15:07

user3265881


1 Answers

renderPrint({}) with your summary statement wrapped up inside is the answer to your issue here on the server side along with the verbatimTextOutput() for the ui side! See step 4 in this link for an example:

This is the code of your app, let’s see a step by step execution of how we create this. We’ve already defined the title panel. Now we’ll define some widgets in our sidebar panel.

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

Here the data we have used is from the already existing library of datasets in R. You can access this dataset by calling the library(datasets) function. We have used the iris dataset here. You can understand about the iris dataset by calling ?iris function in your R Console.

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

verbatimTextOutput("regPrint") will do the trick.

like image 162
Ben Robinson Avatar answered Oct 02 '22 07:10

Ben Robinson