I am new to R and i am using shiny package to build a shiny app that can take different type of queries and those queries takes dynamic user id provided by users on ui level and also i want to show the demo of result of query on ui.
So, my problem is that i am not able to store the query results into an data frame also on clicking on Download button csv is not storing in my system. my code is below. thanks.
###server
library(shiny)
library(RMySQL)
shinyServer(function(input, output) {
datasetInput <- reactive({
switch(input$queryset,
"CDR" = cdr,
"ASSET" = ast,
"USAGE" = usg)
})
output$tbl <- renderTable({
conn <- dbConnect(drv = RMySQL::MySQL(),dbname = "xxxx",
host = "xxxxxx",
username = "xxxxx",
password = "xxxxx"),
q<-dbSendQuery(conn,paste0("select * from table where user_id='",input$user_id,"' and start_time >= '2016-07-16' and start_time < '2016-07-28' order by start_time limit 10 ;",sep = ""
))
dat<- dbFetch(q,n=-1)
on.exit(dbDisconnect(conn), add = TRUE)
})
output$view <- renderTable({
head({dat}, n = input$nrows)
})
output$downloadData <- downloadHandler(
filename = function() { paste(input$user_id, '.csv', sep='') },
content = function(file) {
write.csv({dat}, file)
})
}
)
###ui
library(shiny)
shinyUI(fluidPage(
titlePanel("My App"),
sidebarLayout(
sidebarPanel(
selectInput("queryset", "Choose the type of query:",
choices = c("CDR", "ASSET", "USAGE")),
numericInput("nrows", "Enter the no. of observations:", 10),
numericInput("user_id", "Enter user_id:", 0),
downloadButton('downloadData', 'Download',class = NULL)
),
mainPanel(
tableOutput("view")
)
)
))
Related
I want to upload two csv files and print both tables out.
Here is the code I wrote:
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput(inputId = "files", label = "Choose CSV File", multiple = TRUE,accept = c(".csv")
)
),
mainPanel(
fluidRow(tableOutput("Policy1")),
fluidRow(tableOutput("Policy2")),
)
)
)
server <- function(input, output) {
data <- reactiveValues(file1 = NULL,
file2 = NULL)
output$Policy1 <- renderTable({
if(!is.null(input$files$datapath[1]))
data$file1 <- read.csv(input$files$datapath[1], header = TRUE)
data$file1
})
output$Policy2 <- renderTable({
if(is.null(input$files$datapath[2])) {return(1)}
else{return(NULL)}
})
}
shinyApp(ui, server)
and for the output$Policy2 part, I want to test when the is.null(input$files$datapath[2]) is true. I thought it should be true when I only upload one file or don't upload anything but
if I only upload one csv file, it didn't print out the table 1, which means is.null(input$files$datapath[2]) is false in this case.I don't know why this is the case.
And as a result, if I change the code to ask shiny print two tables for me and only upload one file, there will be an error, here is the code:
library(shiny)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput(inputId = "files", label = "Choose CSV File", multiple = TRUE,accept = c(".csv")
)
),
mainPanel(
fluidRow(tableOutput("Policy1")),
fluidRow(tableOutput("Policy2")),
)
)
)
server <- function(input, output) {
data <- reactiveValues(file1 = NULL,
file2 = NULL)
output$Policy1 <- renderTable({
if(!is.null(input$files$datapath[1]))
data$file1 <- read.csv(input$files$datapath[1], header = TRUE)
data$file1
})
output$Policy2 <- renderTable({
if(!is.null(input$files$datapath[2]))
data$file2 <- read.csv(input$files$datapath[2], header = TRUE)
data$file2
})
}
shinyApp(ui, server)
where I only change a little part and here is the error :
which I assume is because I should return NULL when only one file inputed in, how can I fix this problem, thanks for any help
The value won't be NULL if it's missing. It's better to check that there are enough values checking the length of the vector or something. For example
output$Policy2 <- renderTable({
if(!is.null(input$files) && length(input$files$datapath)>=2)
data$file2 <- read.csv(input$files$datapath[2], header = TRUE)
data$file2
})
I am trying to build a shiny app to retrieve data from an Oracle table based on user specified ID. I want to create one file with data for each ID and download it to the default downloads folder. I would also like to zip the files and provide the user with that one file. Also, the app is just to download the data and I really don't want a main Panel hence the width of the mainPanel is zero. If that's not the way to do it, please let me know.The app is going to reside on a server and hence the need for a download Handler. Below is my code. Any help is greatly appreciated.
library(shiny)
library(ROracle)
library(shinyjs)
library(shinyalert)
library(shinyWidgets)
ui <- fluidPage(
useShinyjs(),
useShinyalert(),
# Application title
titlePanel(fluidRow(
column(10, "RAINFALL AND ET DATA RETRIEVAL",align="center"),
column(2, offset = 0,img(height =90,width=250,src="logo.png",align="left"))
)),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(width = 12,
helpText("Please enter IDs separated by commas. You can enter up to 25 IDs."),
textInput("PixelID", "Pixel ID(s)", value = ""),
helpText("OR"),
fileInput('datafile','Choose csv file to upload Pixel IDs.The csv file should have Pixel IDs in the first column WITHOUT ANY HEADER.',accept = c('csv','comma-separated-values','.csv')),
helpText("Please select a parameter you would like to retrieve."),
radioButtons("ParameterType", "Parameters",
choices = c("Rainfall Estimates","Evapotranspiration Estimates"),
selected = "None"),
dateInput("startdate","Data From", format = "yyyy-mm-dd",max = Sys.Date()),
dateInput("enddate","Data To", format = "yyyy-mm-dd",max = Sys.Date()),
br(), br(),
actionBttn("goButton","Go!",color = "default",style = "fill",size = "lg"),
br(),br(),
uiOutput("download"),
mainPanel(width=0)
)
)
server <- function(input, output, session) {
data<-eventReactive(input$goButton,{
if(is.null(input$PixelID) || input$PixelID == ""){
req(input$datafile)
infile<-input$datafile
PixelList<-read.table(infile$datapath, header = FALSE, sep = ",", stringsAsFactors = FALSE)
colnames(PixelList)<-"PixelNum"
PixelList_comma<-paste(PixelList$PixelNum, collapse = ",")} else{
if(input$PixelID != ""){
PixelList<-data.frame(strsplit(input$PixelID,","))
colnames(PixelList)<-"PixelNum"
PixelList_comma<-input$PixelID
}}
drv <- dbDriver("Oracle")
connection <- dbConnect(drv, username = "xxxx", password = "xxxxx", dbname = "xxxx")
if(input$ParameterType=="Rainfall Estimates"){
for(i in 1:nrow(PixelList)){
raindata<-dbGetQuery(connection, paste("select PIXEL, TO_CHAR(tsdatetime_dt, 'MM/DD/YYYY HH24:MI') as DATE_TIME, tsvalue_ms as RAINFALL from xxxx
where feature_id =",PixelList[i,1]," order by tsdatetime_dt", sep=""))
}
dbDisconnect(conn = connection)
}
return(raindata)
})
output$download <- renderUI({
downloadButton("downloadData", "Download")
})
output$downloadData <- downloadHandler(
filename = function() {
paste("testnexrad",".zip",sep = "")
},
content = function(file) {
for(i in 1:nrow(PixelList)){
#No idea what to do here
}
}
)
}
# Run the application
shinyApp(ui = ui, server = server)
I have a Shiny Application that uses a MongoDB (using mongolite). The application loads and saves to the database with no issues but I am trying to find a way to edit the MongoDB through a datatable(using DT) where when the user edits or deletes a row that they can press an actionbutton to update the mongoDB. When I try to run it currently I am getting
"Warning: Error in : argument must be bson or json."
Is there a way for me to edit from DT, convert it to the JSON Mongo is expecting from the Shiny app? Below is the code.
library(shiny)
library(DT)
library(mongolite)
ui <- fluidPage(
# Application title
titlePanel("MongoTest"),
# Sidebar
sidebarLayout(
sidebarPanel(
actionButton("submit", "Submit"),
actionButton("load","Load"),
actionButton("update","update"),
actionButton("deleteRows", "Delete Rows")
),
#Main UI
mainPanel(
fluidPage(
fluidRow(h2("Interactive Table", align="center")),
tags$hr(),
fluidRow(
DT::dataTableOutput("Interactive_Table")
)
)
)
)
)
server = function(input, output, session){
#Function that loads the information from the mongoDB
loadData <- function() {
# Connect to the database
db = mongo(collection = "collectionhere",db ="SET", url = "mongodb://localhost:27017")
# Read all the entries
data <- db$find()
return(data)
}
READ_IN_DATA=loadData()
values <- reactiveValues(dfWorking = READ_IN_DATA)
#Function that saves data to DB
saveData <- function(data) {
# Connect to the database
db = mongo(collection = "collectionhere",db ="SET", url = "mongodb://localhost:27017")
data <- as.data.frame(t(data))
db$insert(data)
}
updateData = function(data){
# Connect to the database
db = mongo(collection = "collectionhere",db ="SET", url = "mongodb://localhost:27017")
data <- as.data.frame(t(data))
#subjects$update('{}', '{"$set":{"has_age": false}}', multiple = TRUE)
db$update(data)
}
#Loading In the Data
observeEvent(input$load, {
loadData()
})
#Update the DB based off changes to the table
observeEvent(input$update, {
updated_df=as.data.frame(values$dfWorking)
updateData(t(updated_df))
})
#Deleting Rows
observeEvent(input$deleteRows,{
if (!is.null(input$Interactive_Table_rows_selected)) {
values$dfWorking <- values$dfWorking[-as.numeric(input$Interactive_Table_rows_selected),]
}
})
#DT Table
output$Interactive_Table = renderDataTable({
datatable(values$dfWorking,editable=TRUE
)
})
}
# Run the application
shinyApp(ui = ui, server = server)
I try to pull data from Google Analytics with API-R. There are my two files for running my shiny app here:
ui.R
shinyUI(pageWithSidebar(
headerPanel("My Shiny APP"),
sidebarPanel(
dateRangeInput("dateRange",
label = "Select date range:",
start = Sys.Date() - 7, end = Sys.Date()-6)),
mainPanel(
fluidPage(
fluidRow(
column(12,
dataTableOutput("table")
)
)
))))
server.R
ga_token <- authorize(client.id = "XXXXXXXXX.apps.googleusercontent.com",
client.secret = "XXXXXXXXXXX",
cache = "token")
shinyServer(function(input, output){
getDataFromGA <- reactive({
ga.data <- get_ga(profileId = "ga:xxxxxxx",
start.date =input$dateRange[1], end.date = input$dateRange[2],
metrics = c("ga:sessions","ga:bounceRate"), dimensions = "ga:userType",
samplingLevel = "HIGHER_PRECISION", start.index = NULL,
max.results = 10000, include.empty.rows = NULL, fetch.by = NULL, ga_token)
return(ga.data)
})
output$table = renderDataTable({
ga.data <- getDataFromGA()
if (is.null(ga.data)) return(NULL)
})
})
If I put a reactive expression at output$table, I have the same problem (the output table doesn't appear, and R doesn't print me any error message).
Libraries I load: devtools, RGA, shiny.
Instead of simply using reactive, you can try reactiveValues and observeEvent.
Your code may look something like:
values <- reactiveValues(start.date = NULL, end.date = NULL, ga.data = NULL)
observeEvent(input$dateRange, {
values$start.date <- input$dateRange[1]
values$end.date <- input$dateRange[2]
values$ga.data <- get_ga(...) })
You can access the google analytics object as: values$ga.data
I'm building a simple shiny app which will take inputs from the user and fetch data from a table in the DB and take the number of records to be downloaded as an input and provide a download file option.
Everything below works just fine. My only concern is the textInput bar( variable : uiOutput("text") in the ui and output$text in the server) appears only after the datatableOutput is displayed. I do not understand why this happens.
Ideally, I want the textInput bar ('uiOutput("text")') object to be displayed once the leaf(i.e. input$leaf1 is not null) is selected and then I want the datatableOutput to be displayed and then the Download Button should come up.
Is there a way I can achieve this? Thanks
library(shiny)
library(shinydashboard)
#library(stringr)
library(DT)
#library(shinyBS)
ui <- dashboardPage(
dashboardHeader(title = strong("DASHBOARD"),titleWidth = 240),
dashboardSidebar(
sidebarMenu(
selectizeInput("x", "Choose a number:", choices = sort(unique(lftable$x)), multiple = TRUE),
uiOutput("leaf_categ")
)
),
dashboardBody(
fluidRow(
uiOutput("text"),
dataTableOutput("lm_df"),
downloadButton('downloadData', 'Download')
)))
server <- function(input, output){
output$leaf_categ <- renderUI(
selectizeInput("leaf1", "Choose leaf categories:",
choices = reactive(unique(lftable[lftable$num %in% input$x, c("X_NAME")]))(),
multiple = TRUE)
)
#### creates a text input box
#### number of records to be downloaded is provided as input
output$text <- renderUI({
if(is.null(reactive(input$leaf1)())){
return()
}else{
textInput("var1", label = "Enter the number of records to be downloaded", value = "")
}
})
#### fetches data from DB
lm <- reactive({
if(is.null(input$leaf1)){
return()
}else{
leaf_id <- unique(lftable[lftable$X_NAME %in% input$leaf1, c("leaf_id")])
query_str <- paste('select * from table1 where current_date between start_dt and end_dt and score_num >= 0.1 and x in (' , input$x, ')', ' and X_ID in (', leaf_id, ')', ';', sep = "")
}
lm_data <- getDataFrmDW(query_str)
})
###creates a download tab
output$downloadData <- downloadHandler(
filename = function() { paste("lm_user_data", '.csv', sep='') },
content = function(file) {
lm_df <- lm()
lm_df <- lm_df[1:(as.integer(input$text)),]
print(dim(lm_df))
write.csv(lm_df, file, row.names = F)
})
output$lm_df <- DT::renderDataTable(lm())
}
shinyApp(ui, server)