How do I write to a bigquery table from shiny? - shiny

I'm trying to write a shiny app that takes a file as an input and uploads the data in that file to a bigquery table where some other stuff will go on. Everything appears to be working fine in terms of getting the data into my app, but when I try to upload the data to bigquery, nothing happens. No error messages, just nothing.
I can run the code on its own and it executes just fine. I'm having a little trouble figuring out how to create a reproducible example because you can't write to a public dataset, but I've included my code below.
Additional info:
working directory contains my .httr-oauth file
data is visible in my shiny app
Please let me know if there's something I can add to make this question easier to answer. Thanks.
############# UI ############
#
library(shiny)
shinyUI(fluidPage(
# Application title
titlePanel("Upload"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
fileInput('list', 'Choose file to upload',
accept = c(
'text/csv',
'text/comma-separated-values',
'.csv'
)),
tags$hr(),
textInput('sql', 'Or give a query to get the customer_ids you want'),
tags$hr(),
actionButton('go', 'Go')
),
# Show a plot of the generated distribution
mainPanel(
tableOutput('log')
)
)
))
############# server ##############
### setting up the environment
library(shiny)
library(data.table)
library(bigrquery)
### setting up the constants
project <- 'xxxxxxx'
dest_dataset <- 'temp'
dest_table <- 'custs_hash'
cd <- 'CREATE_IF_NEEDED'
wd <- 'WRITE_TRUNCATE'
options(shiny.maxRequestSize = 100*1024^2)
shinyServer(function(input, output) {
logs <- eventReactive(input$go, {
inFile <- input$list
dat <- fread(inFile$datapath)
dat <- head(dat)
return(list(dat = dat))
})
upload <- eventReactive(input$go, {
data <- dat()$dat
ins <- insert_upload_job(project, dataset = dest_dataset, table = dest_table, values = data,
create_disposition = cd, write_disposition = wd)
return(list(ins = ins))
})
output$log <- renderTable(logs()$dat)
})

An eventReactive returns a reactive expression object. Like other reactive objects, you need to expressly call it like a function. Otherwise it won't run by itself.
So in your case, you have upload <- eventReactive(...), then you need to call it using upload().

Related

FileInput Button with selectInput in shiny..!

I am trying to take the speed variable from the "car" data set which I am uploading to the application. Basically Under select speed: I would like to have all the numbers appearing in the dataset$speed. Under selecInput, the choices should depend upond the data set I am uploading using fileInput. How can I complete this task. For now I have added the choices as 1,2,3. In theory there should be all values of the speed variable of cars data set.
library(shiny)
library(datasets)
##the file I am uploading
data(cars)
dataset=write.csv(cars, "dataset.csv")
ui=fluidPage(
actionButton("upload", "Upload File"),
bsModal("uploadFile", " ", "upload",
sidebarLayout(
sidebarPanel(
fileInput("file","Choose file to upload")
),
mainPanel(
tableOutput("contents")
)
)
),
sidebarLayout(
sidebarPanel(
column(3, selectInput("selectElement", "Select speed:", c(1,2,3),multiple =
T, selectize = F)
)
),
mainPanel(
)
)
)
server=function(input,output,session){
output$contents <- renderTable({
inFile <- input$file
if (is.null(inFile))
return(NULL)
read.csv(inFile$datapath)
})
}
shinyApp(ui,server)
My apologies in advance for a somewhat incomplete response: see below.
First of all, an answer to your query:
If you have a dataset like cars, to identify the "speed" labels you can do:
labls <- unique(cars$speed)
...
selectInput("selectElement", "Select speed:", labls, multiple =
T, selectize = F)
I was hoping to post a complete example, but the current logic (maybe because of the limited code posted?) does not seems right: how can the app a) leave to the user to select which file to use; and at the same time b) already filter for speed?
Of course it is possible that you plan to display datasets that have all a column called "speed", then it would make sense :)
Additionally, but this was not part of your question, you appear to use modal dialogues through the package shinyBS.
Since version 0.14 of shiny (around October 2016) shiny has a very good modal function and personally I think it would be better to use the native function instead.
I thougth to post a simple example derived from your code (but with the selectInput for speed commented out because, as mentioned, it does not appear right in the context of the example posted).
library(shiny)
library(datasets)
data(cars)
dataset = write.csv(cars, "dataset.csv")
labls <- unique(cars$speed) # I left this in the code
ui=fluidPage(
sidebarLayout(
sidebarPanel(
actionButton("upload", "Upload File")
),
mainPanel(tableOutput("contents") )
))
server=function(input,output,session){
# Show modal when button is clicked.
observeEvent(input$upload, {
showModal(dataModal())
})
dataModal <- function(failed = FALSE) {
modalDialog(
fileInput('inputId', label=NULL, multiple = FALSE, accept = NULL, width = NULL, buttonLabel = "Browse...", placeholder = "No file selected")
# , selectInput("selectElement", "Select speed:", labls, multiple =
# T, selectize = F)
)
}
output$contents <- renderTable({
if (length(input$inputId )== 0) return(NULL)
inFile <- input$inputId
# if (is.null(input$selectElement )) return(NULL)
input$inputId
})
}
shinyApp(ui,server)

Click on marker to open plot / data table

I'm working on leaflet with shiny. The tools is basic, i have a map with some markers (coming from a table with LONG and LAT).
What I want to do is to open a table or a graph when i click on the marker.
Is there a simple way to do it?
Do you have a really simple example: you have a maker on a map, you click on the marker, and there is a plot or a table or jpeg that s opening?
Here is another example, taken from here and a little bit adapted. When you click on a marker, the table below will change accordingly.
Apart from that, a good resource is this manual here:
https://rstudio.github.io/leaflet/shiny.html
library(leaflet)
library(shiny)
myData <- data.frame(
lat = c(54.406486, 53.406486),
lng = c(-2.925284, -1.925284),
id = c(1,2)
)
ui <- fluidPage(
leafletOutput("map"),
p(),
tableOutput("myTable")
)
server <- shinyServer(function(input, output) {
data <- reactiveValues(clickedMarker=NULL)
# produce the basic leaflet map with single marker
output$map <- renderLeaflet(
leaflet() %>%
addProviderTiles("CartoDB.Positron") %>%
addCircleMarkers(lat = myData$lat, lng = myData$lng, layerId = myData$id)
)
# observe the marker click info and print to console when it is changed.
observeEvent(input$map_marker_click,{
print("observed map_marker_click")
data$clickedMarker <- input$map_marker_click
print(data$clickedMarker)
output$myTable <- renderTable({
return(
subset(myData,id == data$clickedMarker$id)
)
})
})
})
shinyApp(ui, server)
There is a leaflet example file here:
https://github.com/rstudio/shiny-examples/blob/ca20e6b3a6be9d5e75cfb2fcba12dd02384d49e3/063-superzip-example/server.R
# When map is clicked, show a popup with city info
observe({
leafletProxy("map") %>% clearPopups()
event <- input$map_shape_click
if (is.null(event))
return()
isolate({
showZipcodePopup(event$id, event$lat, event$lng)
})
})
Online demo (see what happens when you click on a bubble):
http://shiny.rstudio.com/gallery/superzip-example.html
On the client side, whenever a click on a marker takes place, JavaScript takes this event and communicates with the Shiny server-side which can handle it as input$map_shape_click.

Use Shiny to display bar graph by state

I'm trying to use shiny to create a bar graph for a state that is selected via drop-down box. I'm quite new to R and I've tried a variety of examples to no avail. I have three variables (state, claim #, total $) and for each state there are five values. So something like this:
state <- c("PA", "TX", "NY")
claim_num <- c(1:15)
total <- sample(1000:5000, 15)
df <- (state, claim_num, total)
I want to have something similar to https://beta.rstudioconnect.com/jjallaire/shiny-embedding/#inline-app but I don't know if I can format my data in that was since I would have a lot of NAs.
Do you mean something like this (you can download and run the example)?
library(shiny)
ui <- shinyUI(
fluidPage(
titlePanel("Sample Shiny App"),
sidebarLayout(
sidebarPanel(
uiOutput("stateInput")
),
mainPanel(
plotOutput("statePlot")
)
)
))
server <- shinyServer(function(input, output) {
state <- sample(state.abb, 3, replace = FALSE)
total <- sample(1000:5000, 15)
claimNumber <- 1:15
data <- data.frame(state, total, claimNumber)
output$stateInput <- renderUI({
selectInput(
inputId = "state",
label = "Select a State:",
choices = levels(data$state)
)
})
output$statePlot <- renderPlot({
hist(data$total[data$state == input$state])
})
})
shinyApp(ui = ui, server = server)
What we're doing is taking the list of unique states available in our data frame and passing those to our selectInput that renders as a dropdown in the UI. From here, we can access whatever value the user has selected through the input$state object. More generally, we can access inputs based on whatever we define the inputId to be (in this particular case, we call it state).
Having grabbed the user input, we can then subset the data frame to only return values that correspond to the user-defined state and, in this case, pass those totals values to a plot that we render as output.

Shiny Server Error - could not find function "renderplot"

I am new to Shiny and am trying to add a chord diagram to a shiny server. When I hit the runApp button in RStudio I get the application to run and it generates the UI, but then closes down immediately and I get the following error in the RConsole window: Error in (structure(function (input, output) :
could not find function "renderplot".
Unfortunately, I cannot attach the data as it is proprietary, but I am just creating an adjacency matrix in order to generate the chord plot. The Chord plot works fine outside Shiny. Thanks in advance!
My UI and Server code is below:
library(shiny)
# Starting line
shinyUI(fluidPage(
# Application title
titlePanel("Chord Chart"),
# Sidebar
sidebarLayout(
sidebarPanel(
#Data selection for Chord Chart
selectInput("data","Select a Dataset:",
c("Marine"))),
#The plot created in server.R is displayed
mainPanel(
plotOutput("plot")
)))
)
library(circlize)
library(dplyr)
library(reshape2)
library(manipulate)
library(shiny)
# read marine summaries
marine <- readfile("C:/Personal/R/MarineDataSummary.csv")
# group and summarize by O-D
marine.sum <- marine %>%group_by(Handling_Port, OD_Port_Country) %>%
summarise(tons <-sum(tonnes)) # prepare pivot table
marine.sum1 <- acast(marine.sum, Handling_Port~OD_Port_Country, value.tons="z") # reshape matrix
marine.sum1[is.na(marine.sum1)] <- 0 # set NA to zero
#initialization of server.R
shinyServer(function(input, output) {
output$plot <- renderplot({
c <- chordDiagram(marine.sum1,annotationTrack="grid",preAllocateTracks=list(track.height = 0.3))
##change axis
c <- c + circos.trackPlotRegion(track.index=1, panel.fun=function(x,y) {
xlim = get.cell.meta.data("xlim")
ylim = get.cell.meta.data("ylim")
sector.name=get.cell.meta.data("sector.index")
circos.text(mean(xlim), ylim[1], sector.name,facing="clockwise",
niceFacing=TRUE,adj=c(0,0.4), cex = 0.4)},bg.border=NA)
print(c)
})
})

How to save (not upload) a file created from a Shiny interface?

I have asked this question on the Shiny Google group but once it is published it is immediately deleted, I don't know why.
So I ask this question here.
I know how to upload a file created from a Shiny application but I have unsuccessfully spent a couple of hours to find how to save a file on the hard drive. Please could you show me a way to do so ? For instance I'd like to save a file created with sink() or a RData file.
Below is an (artificial) example of one of my numerous attempts. The sweaveSave() function does not work. Please don't pay attention to the plot, it does not play a role in my question.
server.R
library(shiny)
##
## function creating a Sweave report
##
createReport <- function(file){
sink(file)
cat(
"\\documentclass{article}\n
\\begin{document}\n
\\SweaveOpts{concordance=TRUE}
This is the Rnw file.\n
<<fig=TRUE>>=
plot(0,0)
#\n
\\end{document}\n")
sink()
}
##
## Shiny server
##
shinyServer(function(input, output) {
##
## Create plot
##
createPlot <- reactive({
# generate an rnorm distribution and plot it
titl <- paste0("Exponential distribution with rate ", round(input$parameter,2))
curve(dexp(x,rate=input$parameter), from=0, to=5, main=titl, ylab=NA, xlab=NA)
})
##
## output : plot
##
output$distPlot <- renderPlot({
createPlot()
})
##
## output : download Sweave file
##
output$sweavedownload <- downloadHandler(
filename="report00.Rnw",
content = createReport
)
##
## save Sweave file
##
sweaveSave <- reactive({
if(input$save){
createReport("REPORT00.Rnw")
}else{NULL}
})
})
ui.R
library(shiny)
shinyUI(pageWithSidebar(
# Application title
headerPanel("Hello Shiny!"),
# Sidebar panel
sidebarPanel(
sliderInput("parameter",
"Rate parameter:",
min = 0.0000000001,
max = 10,
value = 5),
checkboxInput("save", "Check to save and download")
),
# Main panel
mainPanel(
plotOutput("distPlot"),
conditionalPanel(
condition = "input.save",
downloadLink("sweavedownload", "Download")
)
)
))
It make it your life easy by using shinyFiles package.
install.package('shinyFiles')
require(shinyFiles)
shinyFilesExample()