JSON Parse Error in MongoDB and R - r

I am new to R and MongoDB and everything related to programming so please bear with me. I am trying to query a MongoDB database based on user input (dropdown menu). When I run the code, I get the following error:
Error: com.mongodb.util.JSONParseException:
{'Name':input$prod}
^
Here is my UI:
mydb <- mongoDbConnect("mysearch")
shinyUI(fluidPage(
titlePanel("MYsearch"),
sidebarPanel(
selectInput("prod", label = "Choose my Product/Service",
choices = list("Engineering", "Operations",
"Detection"), selected = "Engineering")
),
mainPanel(tableOutput("table1"))
)
))
Here is my server:
my <- mongoDbConnect("mysearch")
shinyServer(function(input, output) {
output$table1 <- renderTable({
dbGetQuery(mydb, "usercollection", "{'Name':input$prod}")
})
}
)
Thanks so much for your help.

Try this...
queryParam <- paste('{\'Name\':', input$prod, '}');
shinyServer(function(input, output) {
output$table1 <- renderTable({
dbGetQuery(mydb, "usercollection", queryParam)
})
}
)
Instead of passing the value stored in input$prod, you are passing the string "input$prod" to the function.

Related

How can I update data from SQL in R?

I have a sample database in SQL and an RShiny app. I have a connection to the database and can retrieve the data.
I cannot get the Shiny app to update when new data is adding to the database. I can see how it works with CSV files but am not able to find anything similar for SQL.
This is my code:
library(RODBC)
library(shiny)
dbCon <- odbcConnect("SQL")
df <- sqlFetch(dbCon, "Test")
odbcClose(dbCon)
page_1 <- tabPanel(
tableOutput('table')
)
ui <- navbarPage(
page_1
)
server <- function(input, output, session) {
output$table <- renderTable('table')
myFile <- Q1
data <- reactivePoll(1000, session,
# Returns the time the file was last modified (read that to be SAVED))
checkFunc = function() {
if (file.exists(myFile))
file.info(myFile)$mtime[1]
else
shinyalert(title = "file", text = "There is no such file")
},
# Get file content
valueFunc = function() {
dbCon <- odbcConnect("SQL")
df <- sqlFetch(dbCon, "Test")
odbcClose(dbCon)
output$table <- renderTable('table')
}
)
}
shinyApp(ui = ui, server = server)
I believe I have two problems:
Q1. What should the path for 'myFile' be?
Q2. How should I write the code in the checkFunc function to see if the data has been updated?
Thanks

Use reactive input into R code calculations for Shiny

I have a shiny application reading an input from ui and I am unable to follow up with the data from the input in my code. As below:
ui <- fluidPage(
...
selectInput("ISvModels", "Choose:",
choices = c(1000,5000)),
)
server <- function(input, output) {
vModels <- reactive({input$ISvModels})
qtModels <- length(vModels)
qtModels
vtModels <- paste0("M",1:qtModels," n = ",vModels," scenarios")
vtModels
}
And I get:
Warning: Error in as.vector: cannot coerce type 'closure' to vector of type 'character'
I tried all sort of things from observe to renders but nothing works. Seems I'm missing some concepts here, hope you can help. Thanks!
Your server needs an output, some way for what you've calculated to be shown to the user. We can use a textOutput to achieve this.
Below is a minimal example, showing a dropdown box linked to a textbox.
library(shiny)
ui <- fluidPage(
#Dropdown
selectInput("ISvModels", "Choose:", choices = c(1000,5000)),
#Textbox
textOutput("mytext")
)
server <- function(input, output, session) {
#Prepare Textbox Content
output$mytext <- renderText({
qtModels <- length(input$ISvModels)
vtModels <- paste0("M", 1:qtModels, " n = ", input$ISvModels," scenarios")
return(vtModels)
})
}
shinyApp(ui, server)

Can you parse an XML into R Shiny and view as a data frame?

I'm new to R-shiny and I'm trying to develop an R-shiny application that would allow the user to upload an XML file, view the table as a data frame, and then download it as a CSV.
I've so far had no luck anywhere trying to find info on parsing XML's into R-shiny. Below is some code that I found from someone else's post on here which allows you to read in an XML and it will display the raw text, but I'm looking to get a proper data frame so that I can do some analysis on the data that the user uploads.
library(shiny)
ui <- fluidPage(
fileInput("File", "Choose file"),
tableOutput("Data")
)
server <- function(input, output, session) {
Data <- eventReactive(input$File, {
read_xml(input$File$datapath)
})
output$Data <- renderTable({
head(xml_text(Data()))
})
}
shinyApp(ui, server)
The code to do what I need in R is very simple, but converting this over to R-shiny is causing me lots of trouble.
data <- xmlParse("C:/filepath/data.xml")
df <- xmlToDataFrame(data, nodes =getNodeSet(data, "//nm:Row",
namespaces=c(nm = "urn:schemas-microsoft-com:office:spreadsheet")))
Can anyone help please?
Thanks in advance!
You can use package XMLthe same way you do in base R:
library(shiny)
library(XML)
ui <- fluidPage(
fileInput("File", "Choose file"),
tableOutput("Data")
)
server <- function(input, output, session) {
df <- eventReactive(input$File, {
xmlToDataFrame(input$File$datapath)
})
output$Data <- renderTable( head( df()))
}
shinyApp(ui, server)
Update: I've managed to solve the issue by writing a function that converts the "table" node of the xml into a data frame, and calling this function from within the server.
converter <- function(xml_data){
data <- xmlParse(xml_data)
df <- xmlToDataFrame(data, nodes =getNodeSet(data, "//nm:Row",
namespaces=c(nm = "urn:schemas-microsoft-com:office:spreadsheet")))
colnames(df) <- df[1,]
df <- df[-1, ]
return(df)
}
ui <- fluidPage(
fileInput("File", "Choose file"),
tableOutput("Data")
)
server <- function(input, output, session) {
df <- eventReactive(input$File, {
converter(input$File$datapath)
})
output$Data <- renderTable( head( df()))
}
shinyApp(ui, server)

How can we give custom error message in R shiny for the app?

I have created a shiny app which takes the select query from the user inside a textarea field and then runs it when the user clicks on Go. And the data is shown in the table below that.
Now if the user enters some wrong query, or if there is any mistake in the query then the user should get an Error Message "Please correct the query!".
Right now I am getting this error message "An error has occurred. Check your logs or contact the app author for clarification" if the user enters anything wrongly in the textarea box. I am getting this even after I removed the sanatize error line from my code.
Any help would be much appreciated
server <- function(input, output, session) {
resultTable <- data.frame()
observeEvent(input$tableName, {
nQuery = paste("SELECT * FROM ",db, ".dbo.[",input$tableName,"]" ,sep = "" )
updateTextAreaInput(session, "query", value = nQuery)
})
observeEvent(input$runQuery, {
resultTable <<- sqlQuery (channel = conn, query = input$query)
output$table <- renderDataTable(resultTable)
}
)
}
If you install GitHub version of shinyWidgets, you'll have a function execute_safely to display error in a popup :
# Install dev version
devtools::install_github("dreamRs/shinyWidgets")
# then something like that:
library(shinyWidgets)
server <- function(input, output, session) {
resultTable <- data.frame()
observeEvent(input$tableName, {
nQuery = paste("SELECT * FROM ",db, ".dbo.[",input$tableName,"]" ,sep = "" )
updateTextAreaInput(session, "query", value = nQuery)
})
result <- eventReactive(input$runQuery, {
execute_safely(sqlQuery (channel = conn, query = input$query))
})
output$table <- renderDataTable(result())
}
Reproducible example:
library(RSQLite)
library(shiny)
# dev: devtools::install_github("dreamRs/shinyWidgets")
library(shinyWidgets)
# Fake database
con <- dbConnect(RSQLite::SQLite(), ":memory:")
dbWriteTable(con, "mtcars", mtcars) # write a table
ui <- fluidPage(
textAreaInput(inputId = "query", label = "Query:", value = "SELECT * FROM mtcars"),
actionButton(inputId = "runQuery", label = "Run query"),
tableOutput("table")
)
server <- function(input, output, session) {
result <- eventReactive(input$runQuery, {
execute_safely(dbGetQuery(conn = con, statement = input$query))
})
output$table <- renderTable(result())
}
shinyApp(ui, server)
If you write a bad query, you'll get an error popup :

How can I prevent RMySQL errors and show to user in Shiny?

I have a Shiny App that executes a query to a MySQL database like this example:
UI
textAreaInput("query")
SERVER
data <- reactive({
df<-dbGetQuery(conection, input$query)
return(df)
})
The problem is that when the user types a wrong syntax in the textAreaInput the Shiny App closes and the error is shown in the R Console.
What I want is to print that error in the app so the user can try again and write another query.
Can someone help me please?
We can use tryCatch. Here is a complete example based on #Fan Li's answer here
library(RSQLite)
con <- dbConnect(SQLite(), dbname="sample.sqlite")
dbWriteTable(con, "test", data.frame(value1 = letters[1:4], value2 = letters[5:8]))
dbDisconnect(con)
library(shiny)
library(RSQLite)
runApp(list(
ui = bootstrapPage(
#select * from te fail
#select * from test work
textAreaInput("query",'Query'),
actionButton("action", label = "Run Query"),
hr(),
tableOutput("table")
),
server = function(input, output){
#Reactive is eager by definition and it will signal unreal/annoying errors, hence I used eventReactive
data <- eventReactive(input$action,{
tryCatch({
con <- dbConnect(SQLite(), dbname="sample.sqlite")
data<-dbGetQuery(con, input$query)
dbDisconnect(con)
return(data)
},
error = function(e){
showModal(
modalDialog(
title = "Error Occurred",
tags$i("Please enter valid query and try again"),br(),br(),
tags$b("Error:"),br(),
tags$code(e$message)
)
)
})
})
output$table <- renderTable(data())
}))

Resources