r shiny error Error in as.vector(x, “character”) : cannot coerce type 'closure' to vector of type 'character'

断了今生、忘了曾经 提交于 2020-02-16 06:57:26

问题


While trying to pass an user entered input (empId) from Shiny UI into a sql query on shiny server.r not sure how to debug this error.

 Error in as.vector(x, "character") : 
 cannot coerce type 'closure' to vector of type 'character'

UI.r

library(shiny)

shinyUI(fluidPage(
titlePanel("Employee Table (AdventureWorks)"),
sidebarLayout(
sidebarPanel((""),
             textInput("idnumb", "Employee ID number",""),
             submitButton("Ok")),
             mainPanel(tableOutput("emptitle")))))

Server.r

 shinyServer(function(input, output) {
 library(RODBC)
 library(sqldf)
 a1 = reactive({ (input$idnumb) })
 acc_con1 = odbcConnect("AdvWrk", uid="... ", pwd="... ")
 sql1 = sqlQuery(acc_con1, paste0('select Title from dbo.Employee where EmployeeID=',a1))
 output$emptitle = renderTable(print(sql1))
 })

To test if my query works , I tired this with the actual EmployeeID in the sql like this below

  .
  .
  sql1 = sqlQuery(acc_con1, paste0('select Title from dbo.Employee where EmployeeID = 8'))
  .
  .

I get a normal ouput,

  Title
  Production Technician - WC10 

When I try to make this reactive to user input i see Error in as.vector(x, "character") : cannot coerce type 'closure' to vector of type 'character...error...Need help.


回答1:


Main problem in your code is that you give reactive function "a1" as argument to sqlQuery function. sqlQuery expects you to give character as argument.

In this case where you want to monitor any changes in input. You could use observe function. I also added error checking line to make sure that you actually have some value in a input$idnumb

shinyServer(function(input, output) {
         library(RODBC)
         library(sqldf)
            observe({
            if(input$idnumb ==NULL)
               return(NULL)
            acc_con1 = odbcConnect("AdvWrk", uid="... ", pwd="... ")
            sql1 = sqlQuery(acc_con1, paste0('select Title from dbo.Employee where EmployeeID=',input$idnumb))
            )}
        output$emptitle = renderTable(print(sql1))
 )}



回答2:


I also agree with @Mikael Jumppanen that

Main problem in your code is that you give reactive function "a1" as argument to sqlQuery function. sqlQuery expects you to give character as argument.

However the solution is much simpler: you should simply call a1() instead of a1 since you have defined it as a reactive function.

 sql1 = sqlQuery(acc_con1, paste0('select Title from dbo.Employee where EmployeeID=',a1()))

Can you please try it?



来源:https://stackoverflow.com/questions/28757709/r-shiny-error-error-in-as-vectorx-character-cannot-coerce-type-closure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!