I am pulling in a query results in my R shiny app. I want to be able to see the format of the results before i create functions to do what i need for my app. This is the basic setup for my R shiny app
#libraries
library(DBI)
library(rJava)
library(RJDBC)
#the driver is a JDBC if that helps
con <- dbConnect(drv, url "some url")
my_query = "select * from my_table"
print(my_query)
server <- function(input, output, session){
}
ui=shinyUI(fluidPage(
))
shinyApp(ui = ui, server = server)
This just gives me
[1] "select * from my_table"
in the console in RStudio
How can i show my query results in the console of R studio for my shiny app?
Here you need to pass the output from the server to the ui. In the server you should have the code that will fetch the data from query. After that the output is passed to ui.
Try your code in the below format. It is only an indicative example. Please update this code with your original parameters.
library(DBI)
library(rJava)
library(RJDBC)
server <- function(input, output, session){
con <- dbConnect(drv, url "some url")
output$table1 <- renderTable({
my_query = "select * from my_table"
dbGetQuery(con,my_query)
})
}
ui=shinyUI(fluidPage(
tableOutput("table1")
))
shinyApp(ui = ui, server = server)
Sumanta's answer is right, however remember to close the connection to the database.
df <- dbGetQuery(con,my_query)
on.exit(RJDBC::dbDisconnect(con))
To check for format you could use
str(df) # as some people have mentioned above
# or
glimpse(df)
Related
The below example code "Code" saves to the browser the user slider input from one session to the next, using package shinyStorePlus. I would like the user to be able to clear the saved inputs via a click of the "clear" actionButton(). When the commented-out code in "Code" is uncommented, revealing the clear function in the server section, clicking that actionButton() results in error Warning: Error in envir$session$sendCustomMessage: attempt to apply non-function. However, if I pull the clear data code of clearStore(appId = appid) out of the observer and run the code this way, it works fine in clearing out the saved browser data. As an example, running the "Isolated Clearing Code" at the very bottom, completely outside the observer, clears out the browser data like it should.
What am I doing wrong here with my use of an observer? I've fooled around with using isolate(), making the appid reactive, etc., and nothing seems to work.
Code:
library(shiny)
library(shinyStorePlus)
ui <- fluidPage(
initStore(), br(),
sliderInput("input1",label=NULL,min=1,max=200,value=100),
actionButton("clear","Clear data")
)
server <- function(input, output, session) {
appid <- "application001"
setupStorage(
appId = appid,
inputs = list("input1")
)
# observeEvent(input$clear,{
# clearStore(appId = appid)
# })
}
shinyApp(ui, server)
Isolated Clearing Code:
ui <- fluidPage(
initStore(),
)
server <- function(input, output, session) {
appid <- "application001"
clearStore(appId = appid)
}
shinyApp(ui, server)
This seems to be an issue with shinyStorePlus' code:
> clearStore
function (appId)
{
envir <- parent.frame()
envir$session$sendCustomMessage("clearStorage", appId)
}
using parent.frame() to get the session is unfavorable.
Please check the following instead:
library(shiny)
library(shinyStorePlus)
clearStore <- function(appId, session = getDefaultReactiveDomain()){
session$sendCustomMessage("clearStorage", appId)
}
ui <- fluidPage(
initStore(), br(),
sliderInput("input1",label=NULL,min=1,max=200,value=100),
actionButton("clear","Clear data")
)
server <- function(input, output, session) {
appid <- "application001"
setupStorage(
appId = appid,
inputs = list("input1")
)
observeEvent(input$clear,{
clearStore(appId = appid)
})
}
shinyApp(ui, server)
I left a PR here.
In my shiny server I am figuring out the name of a markdown file which I want to show in the UI. I know how to pass the file name, as a string, back to the UI but I don't now how to tell includeMarkdown() to treat the string as a file name.
My code so far is below. Any advice?
library(shiny)
fileConn<-file("hello.md")
writeLines(c("# Hello","# World"), fileConn)
close(fileConn)
ui <- fluidPage(
includeMarkdown("hello.md"),
br(),
div("File name text:", textOutput("fileNameText", inline = TRUE)),
#includeMarkdown(fileNameText) # this needs help
)
server <- function(input, output, session) {
selectedName <- reactive({
paste0("hello.md") # this is actually more complicated...
})
output$fileNameText <- renderText(
paste0(selectedName())
)
}
shinyApp(ui = ui, server = server)
Your example code works fine, but from your description, I am thinking your asking how to pass a different filename to includeMarkdown() that was created somewhere else in the app, correct?
The first step is to understand includeMarkdown() as a UI element that will change depending on other UI elements (and stuff that happens in server). The solution is to use a placeholder in the ui to hold the place for the includeMarkdown() element, and create that particular element in server using renderUI.
Hopefully you can follow this example. I'm using uiOutput('displayFile') to hold the place for the element that's created in server.
library(shiny)
fileConn<-file("hello.md")
writeLines(c("# Hello","# World"), fileConn)
close(fileConn)
fileConn1<-file("goodbye.md")
writeLines(c("# Goodbye","# Everyone!"), fileConn1)
close(fileConn1)
ui <- fluidPage(
selectInput('file_selection', 'Choose Markdown File:', choices=c('hello.md','goodbye.md')),
uiOutput('displayFile')
)
server <- function(input, output, session) {
output$displayFile <- renderUI({
includeMarkdown(input$file_selection)
})
}
shinyApp(ui = ui, server = server)
Why can't my code run successfully? How do I use sjPlot to create a html table in shiny?
library(shiny)
library(sjPlot)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(),
mainPanel(htmlOutput("a"))
)
)
server <- function(input, output){
output$a <- renderUI({
tab_df(iris,title="title",col.header='N',footnote='footnote')
})
}
# Run the application
shinyApp(ui = ui, server = server)
When I run the code , the log is "Warning: Error in if: argument is of length zero". I don't know what's wrong with the code.
Thanks.
The problem is that tab_df seems to write its HTML out to a file rather than return the HTML that you want to use. Looking at the sjPlot:::print.sjTable, it seems like we can get around that with
server <- function(input, output){
output$a <- renderUI({
HTML(tab_df(iris,title="title",col.header='N',footnote='footnote')$knitr)
})
}
I'm building an RShiny App and I'd like to have users be able to navigate to a directory and then I want to be able to use this directory name in a function. There are several similar questions out there, but nothing I've been able to work out for my problem. I created a simple reproducible example.
In this example, I'd like to be able to take the path_prefix and pass it to a system command so that I can change to this directory. I'm having the function print the path_prefix in the Shiny window and what is printed is appropriate. However, the functions I'm using turn the path into a list where each folder is in quotes. Does anyone have suggestions for how this could work?
library(shiny)
library(shinyFiles)
# UI
ui <- fluidPage(
shinyDirButton('path_prefix', 'Select a directory', title='Select a directory'),
textOutput('path_prefix'),
actionButton("run", "run test")
)
# Server
server <- function(input, output, session) {
volumes <- getVolumes()
shinyDirChoose(input, 'path_prefix', roots=volumes, session=session)
dirname <- reactive({parseDirPath(volumes, input$path_prefix)})
# Observe input dir
observe({
#fileinfo <- parseSavePath(volumes, input$path_prefix)
if(!is.null(dirname)){
print(dirname())
output$path_prefix <- renderText(dirname())
}
})
observeEvent(input$run, {
system(paste0("cd ", input$path_prefix))
})
}
shinyApp(ui = ui, server = server)
I'm facing a problem with R shiny and sqlite. My app is supposed to authenticate the user and load his/her preferences.
Here is my code :
server.R
library(shiny)
library(shinyBS)
library(dplyr)
library(lubridate)
library(DBI)
library(RSQLite)
############################
# Database functions #
###########################
# Connect the user to the dtabase app
connect <- function(userName,pwd){
#Put a generic path here
db <- dbConnect(SQLite(), dbname = "my_path/database.db")
#Query to get the correct passwd
qry = paste('SELECT password from USERS where name = "',userName,'"')
res= dbGetQuery(db,qry )
ifelse(res==pwd,"connected","unable to connect to the database")
dbDisconnect(db)
}
function(input, output,session) {
observeEvent(input$connectButton, {
userName= renderPrint(input$username)
print(userName)
userPwd = paste(input$password)
connect(user = userName,pwd = userPwd)
})
ui.R
shinyUI(fluidPage(
titlePanel("Authentification"),
textInput('username', label="User name"),
textInput('password', label= "password"),
actionButton("connectButton", label='Connect'),
actionButton("subscribeButton",label='Subscribe')
)
)
app.R
library(shiny)
library(shinyBS)
####### UI
ui <- source("ui.R")
####### Server
varserver <- source("server.R")
####### APP
shinyApp(ui = ui, server = varserver)
My problem is when I want to put the content of the TextInput for the queries. I've tried several methods
With the current version, renderPrint(input$username) returns me something what seems to be a function but it doesn't seem to be useful.
I also tried an other way using only
userName=paste(input$userName)
This returns me the content of the textField but when i integrate it to the query it puts
[1] "SELECT password from USERS where name = \" test \""
and then I got the error
Warning: Error in matrix: length of 'dimnames' [2] not equal to array extent
My objective is to have a query like this
"Select password FROM USERS where name = "username"
with username representing the content of the TextInput.
EDIT
I know use this version for the query, and it put a syntaxly correct query
qry = paste0('SELECT password from USERS where name = \'',userName,'\'')
res= dbGetQuery(db,qry )
but I face this problem now :
Warning: Error in matrix: length of 'dimnames' [2] not equal to array extent
when I run the method
connect(db,qry)
I think the problem comes from the way i get the content of the TextInput : I use
function(input, output,session) {
observeEvent(input$connectButton, {
userName= paste0(input$username)
userPwd = paste0(input$password)
connect(user = userName,pwd = userPwd)
})
What do you think about this ?
I found a solution which work
connect <- function(userName,pwd){
#Put a generic path here
db <- dbConnect(SQLite(), dbname = "my_path/database.db")
#Query to get the correct passwd
qry = paste0("SELECT password from USERS where name = \'",userName,"\'")
res= dbGetQuery(db,qry )
res = paste0(res)
ifelse(res==pwd,print("connected"),print("unable to connect to the database"))
dbDisconnect(db)
}
I just cast arguments between simple quotes