将闪亮的UI文本输入传递到rmongodb查询中

时间:2015-06-29 18:49:41

标签: shiny-server rmongodb shiny

以下是我的代码的简化版本。我只是想让Shiny将输入值传递给rmongodb查询,根据用户输入运行查询,然后绘制变量的平均值。下面的代码包括复制我的问题所需的一切,包括将文档插入集合中。

我非常感谢任何帮助!我把头发拉了出来(开头没太多了)。我怀疑我正在不恰当地放置reactive()命令或沿着那些行放置。

非常感谢能提供帮助的任何人。

#Install required packages and call each
library(devtools)
install_github(repo = "mongosoup/rmongodb")
library(rmongodb)
library(shiny)

#Establish connection with mongodb, check status, name database and collection, insert some documents, return one document
mongo <- mongo.create()

mongo.insert(mongo, "simpledb.main",'{"user":"Joe", "age":34}')
mongo.insert(mongo, "simpledb.main",'{"user":"Joe", "age":31}')
mongo.insert(mongo, "simpledb.main",'{"user":"Joe", "age":53}')
mongo.insert(mongo, "simpledb.main",'{"user":"Kate", "age":29}')
mongo.insert(mongo, "simpledb.main",'{"user":"Lisa", "age":21}')
mongo.insert(mongo, "simpledb.main",'{"user":"Henry", "age":34}')
mongo.insert(mongo, "simpledb.main",'{"user":"David", "age":43}')

if(mongo.is.connected(mongo) == TRUE) {
  help("mongo.count")
  mongo.count(mongo, "simpledb.main")
}

if(mongo.is.connected(mongo) == TRUE) {
  mongo.find.one(mongo, "simpledb.main")
}

#Code needed for Shiny UI
ui <- fluidPage(
  fluidRow(
    column(2, textInput(inputId = "userName", label = "", value = "Enter name here"))),
  mainPanel(plotOutput(outputId = "main_plot"))
)

#Code needed for Shiny server
server <- function(input, output) {

  queryReactive <- reactive({
     nameFinal <- paste0(input$userName)
     query = mongo.bson.buffer.create()
     mongo.bson.buffer.append(query, "user", nameFinal)
     query = mongo.bson.from.buffer(query)
  })
 #Run the query and store results as an R list object
 queryresults <- mongo.find.all(mongo=mongo, ns = coll, query=queryReactive)

 #Convert the R list object into a data frame
 resultsdf <- data.frame(matrix(unlist(queryresults), nrow=length(queryresults), byrow=T), stringsAsFactors=FALSE)

  output$main_plot <- renderPlot({boxplot(as.numeric(resultsdf$X3))})

}

#Code needed to call Shiny UI and server
shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:0)

您的服务器功能不需要响应命令。我已在下面简化并更正了您的功能:

server <- function(input, output) {

  output$main_plot <- renderPlot({
    nameFinal <- paste0(input$userName)
    query = mongo.bson.buffer.create()
    mongo.bson.buffer.append(query, "user", nameFinal)
    query = mongo.bson.from.buffer(query)
    queryresults <- mongo.find.all(mongo=mongo, ns = "simpledb.main", query=query)
    if (length(queryresults) > 0) {
        resultsdf <- data.frame(matrix(unlist(queryresults), nrow=length(queryresults), byrow=T), stringsAsFactors=FALSE)
        boxplot(as.numeric(resultsdf$X3))
    }
    else boxplot(c(0))
 })

}