如何使用R填充数据库中的下拉列表?

如何使用R填充数据库中的下拉列表?,r,shiny,R,Shiny,我想用数据库查询的结果填充R应用程序中的淹没列表 #I have a global.r file where i put this code: getData<- function() { ....this function returns a single column of names. I tested that it does work. } #Now in my ui.r file I try to use the function to populate a dropdo

我想用数据库查询的结果填充R应用程序中的淹没列表

#I have a global.r file where i put this code:
getData<- function()
{
  ....this function returns a single column of names. I tested that it does work.
}

#Now in my ui.r file I try to use the function to populate a dropdown list like:
source('global.r')
shinyUI(pageWithSidebar(
selectInput("names", "Select Data",getData(),selected="Name 1" multiple = FALSE)
),
#我有一个global.r文件,其中我放了以下代码:

getData如果您希望下拉列表是被动的,请使用uiOutput(“名称”)而不是在ui.R中选择Input。然后在服务器.R中,您需要一个类似以下的函数:

output$names<-renderUI({
  selectInput("names", "Select Data", choices=getData(), selected=names[1])
})

output$names确保通过查询检索的列具有名称

如果使用
dbGetQuery
从数据库中获取结果,结果将以数据帧的形式返回,即使它只是一列

res <- dbGetQuery(conn, 'select column_name from table_name')
is.data.frame(res) # this will be true

res实际上我不知道问题来自哪里,如果getData返回一个向量,它应该可以工作。但是不要在你的Ui中
source('global.r')
,如果getData被认为是被动的,它将不会工作,因为Ui.r只运行一次(在应用程序加载时)。如果global.r、ui.r和server.r在同一目录中,则在运行应用程序时,global.r将自动来源。好的,我从ui.r页面中取出了来源('global.r')。现在我得到了一个错误:if(!is.na(attribValue)){:条件的长度大于1,并且只使用第一个元素,
getData
返回的对象的str是什么?getData()返回一个名称列表,如:Bob、Joe、Harry等。它是一列数据。它看起来像:rbind(“Joe”、“Bob”、“Harry”)您可能只需要一个简单的数据向量。请尝试通过
getData()[,1]
get_data <- function(){
  conn <- dbConnect(jdbcDriver, Connection_string)
  on.exit(RJDBC::dbDisconnect(conn))
  q <- "SELECT distinct split_part(column_name, '.', 1) from table_name;"
  return (dbGetQuery(conn, q))
}
get_data <- function(){
  conn <- dbConnect(jdbcDriver, Connection_string)
  on.exit(RJDBC::dbDisconnect(conn))
  q <- "SELECT distinct split_part(column_name, '.', 1) my_name from table_name;"
  return (dbGetQuery(conn, q))
}