Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can I refresh the data import in shiny automatically ? #828

Closed
janeshdev opened this issue May 15, 2015 · 7 comments
Closed

How can I refresh the data import in shiny automatically ? #828

janeshdev opened this issue May 15, 2015 · 7 comments

Comments

@janeshdev
Copy link

janeshdev commented May 15, 2015

Hi, I am using googlesheets data and importing it into shiny to plot data. I want to create a button which would automatically start the whole execution of the processes. How do I do that ? The code I have is as follows:

ui.R

library(shiny)
library(ggplot2)
library(dplyr)
library(rCharts)
library(DT)
library(htmlwidgets)
library(shinyapps)
library(httr)
library(googlesheets)

# dataset <- ntctidecombined

# Define UI for application that draws a histogram
shinyUI(fluidPage(

  # Application title
  titlePanel("Nepal Seattle Society fund raise"),



  # Sidebar with a slider 
  sidebarLayout(position="left",
                sidebarPanel( 

                  # adding the new div tag to the sidebar            
                  tags$div(class="header", checked=NA,
                           tags$p("Nepal Seattle Society is a non-profit organization in Seattle. Currently Nepal Seattle Society is showing its effort by conducting various programs such as fund raise dinner, prayer at buddhist monastery, Seattle Peace walk etc to support the earthquake victims in Nepal. This application shows the summary of the effort by Nepal Seattle Society on Fund raise dinner program hosted by `The Mountaineers`."),
                           tags$a(href="http://www.nepalseattle.org/index.php", "Nepal Seattle Society")
                  )

                ),

                mainPanel(
                  #       plotOutput('plot', height="700px"))
                  tabsetPanel(
                    tabPanel("Fund raise dinner", plotOutput("plot", width = "700px", height = "600px")),
                    tabPanel("Ticket sales", tableOutput("donors")),
                    tabPanel("Summary", tableOutput("table"))
                  ))

  )
))

server.R

library(shiny)
library(ggplot2)
library(dplyr)
library(rCharts)
library(DT)
library(htmlwidgets)
library(shinyapps)
library(httr)
library(googlesheets)

gap_url <- "https://docs.google.com/spreadsheets/d/1J4uXPrLlKL_-4cWLPg2kBZyxnDFiGhld5Tmj0WENtAQ"
gap <- gap_url %>% gs_url()

shinyServer(function(input, output) {

  seattle <- gap %>% get_via_csv(ws = "Dinner_tickets")
  seattle <- seattle %>% filter(tolower(Status) == "sold")

#   seattle$Amount <- as.numeric(seattle$Amount)
  seattle$price <- ifelse(seattle$Ticket.type =="VIP", 50, ifelse(seattle$Ticket.type == "General", 30, "NA"))
  seattle$price <- as.numeric(seattle$price)  

  summaryseattle <- seattle %>% group_by(Ticket.type) %>% summarise(Sum = sum(price))
  names(summaryseattle) <- c("Category", "Sum")

  output$plot <- renderPlot({

    p1 <- ggplot(summaryseattle, aes(x = Category, y = Sum, fill = Category)) + 
      geom_bar(stat= "identity") + ylab("Total Amount (dollars)") +
      geom_text(aes(Category, Sum, label = Sum, vjust = -0.5)) + 
      coord_cartesian(ylim = c(0,10000)) + ggtitle(paste("Total amount collected so far from ticket sales is $", sum(summaryseattle$Sum)))
    p1  

  })

  output$table <- renderTable(summaryseattle)
  output$donors <- renderTable(seattle)

})
@wch
Copy link
Collaborator

wch commented Jun 1, 2015

The usual way to do this is to add an actionButton and make the relevant outputs or reactives depend on it. So, for example, your renderPlot() would look something like this:

  output$plot <- renderPlot({
    input$go_button # This makes the renderPlot depend on the go_button

    p1 <- ggplot(summaryseattle, aes(x = Category, y = Sum, fill = Category)) + 
      geom_bar(stat= "identity") + ylab("Total Amount (dollars)") +
      geom_text(aes(Category, Sum, label = Sum, vjust = -0.5)) + 
      coord_cartesian(ylim = c(0,10000)) + ggtitle(paste("Total amount collected so far from ticket sales is $", sum(summaryseattle$Sum)))
    p1  
  })

See the action button article for more information.

@wch wch closed this as completed Jun 1, 2015
@sorenoneill
Copy link

I'm having a similar issue, and I don't thing the reply by @wch actually solves the issue: how to refresh data import.

As far as i can tell, wch's solution refreshes the plot, but not the imported data..

I have tried to fix this - so far without luck.

This is my minimally not-working example, which makes use of observeEvent and reactiveValues.

For the MnWE I've provided a simple google sheet (should be accessible and editable via this link: https://docs.google.com/spreadsheets/d/1s1ZMQgyesYOIjIJb31chtONaiRjhXezN3xqpKSP9_hk/edit?usp=sharing

Changing the google sheet and 'reloading' in the script below does not scratch my itch :-(

Server:

library(shiny)
library(gsheet)

shinyServer(function(input, output) {

  observeEvent(input$reload, {
    data <- reactiveValues()
    url <- "https://docs.google.com/spreadsheets/d/1s1ZMQgyesYOIjIJb31chtONaiRjhXezN3xqpKSP9_hk/edit?usp=sharing"
    data <- gsheet2tbl(url)
  })

  output$table <- renderDataTable(data)

})

UI:

library(shiny)

shinyUI(fluidPage(

  fluidRow(
    column(3,
      dataTableOutput('table'),
      actionButton(inputId = "reload", label = "Reload data")
    )
  ) 
))

@jcheng5
Copy link
Member

jcheng5 commented Apr 13, 2016

  1. reactiveValues() returns a list-like object, whose intended usage is that you set its elements. So data$sheet <- gsheet2tbl(url) and then renderDataTable(data$sheet), for example.
  2. Rather than observeEvent, you can use eventReactive:
data <- eventReactive(input$reload, {
  url <- "https://docs.google.com/spreadsheets/d/1s1ZMQgyesYOIjIJb31chtONaiRjhXezN3xqpKSP9_hk/edit?usp=sharing"
  gsheet2tbl(url)
}, ignoreNULL = FALSE)

output$table <- renderDataTable(data())

The ignoreNULL argument lets you control whether the eventReactive should wait until you've clicked once to execute the first time. So ignoreNULL = TRUE (the default) would mean the data doesn't show at all until you hit the button.

@sorenoneill
Copy link

That was very helpful and I think I'm almost there ... perhaps google sheets is not the best way to go, but now it's become a matter of principle :-)

The following still doesn't work for me however, which I really expected it to ..

server.R

library(shiny)
library(gsheet)

shinyServer(function(input, output) {

  fetch <- reactiveValues()

  fetch$data <- eventReactive(input$reload, {
    url <- "https://docs.google.com/spreadsheets/d/1s1ZMQgyesYOIjIJb31chtONaiRjhXezN3xqpKSP9_hk/edit?usp=sharing"
    gsheet2tbl(url)
  }, ignoreNULL = FALSE)

  output$dataTable <- renderDataTable(fetch$data)

})

ui.R

library(shiny)

shinyUI(fluidPage(

  fluidRow(
    column(3,
      tableOutput('dataTable'),
      actionButton(inputId = "reload", label = "Reload data")
    )
  ) 
))

@sorenoneill
Copy link

sorenoneill commented Apr 21, 2016

@wch I hope I'm not being a pain ... but I'm completely stumped here. I've tried and tried again over the last three days. I posted at google groups and via IRC without luck. I have read the fine manual online but I simply can not see why this shouldn't work

library(shiny)
library(googlesheets)

shinyServer(function(input, output) {

  RV <- reactiveValues()

  observeEvent(input$reload, {
    RV$data <- gs_read( gs_key("1s1ZMQgyesYOIjIJb31chtONaiRjhXezN3xqpKSP9_hk") )
  }, ignoreNULL=FALSE)

  output$dataTbl <- renderDataTable(RV$data)

  output$clics <- renderText(input$reload)

})
library(shiny)

shinyUI(fluidPage(

  fluidRow(
    column(3,
           tableOutput('dataTbl'),
           actionButton(inputId = "reload", label = "Reload data"),
           textOutput('clics')
    )
  ) 
))

When I run the app -- the actionButton shows up and from the console (see below) I gather the google spread sheet is loaded into memory. Clicking the button causes the textOutput('clics') to update and prints the number to the web page ... but the tableOutput('dataTbl') doesn't

I have tried a number of other possible way (e.g. using RV$data <- eventReactive instead of observeEvent)

@jcheng5
Copy link
Member

jcheng5 commented Apr 23, 2016

You're using tableOutput and renderDataTable. You should either use dataTableOutput and renderDataTable, or alternatively, tableOutput and renderTable.

That said, I also recommend you do it the eventReactive way, even though this method with reactiveValues/observeEvent will work. You can watch my "Effective reactive programming" tutorial to learn more.

@sorenoneill
Copy link

I did catch you reply and it was very helpful ... It's working for me now

Thanks a lot for you help and excellent work with Shinyapps ..

Kind regards
Soren - Denmark

On 23 April 2016 at 18:22:50 +02:00, Joe Cheng notifications@github.com wrote:

You're using tableOutput and renderDataTable. You should either use dataTableOutput and renderDataTable, or alternatively, tableOutput and renderTable.
That said, I also recommend you do it the eventReactive way, even though this method with reactiveValues/observeEvent will work. You can watch my "Effective reactive programming" tutorial https://www.rstudio.com/resources/webinars/shiny-developer-conference/ to learn more.


You are receiving this because you commented.
Reply to this email directly or view it on GitHub #828 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants