我是R的新手我正在尝试使用我创建的sql数据库在Shiny中绘制控制图。在下面的代码中,我能够按日期获取sql数据。但我无法访问必须为其绘制图形的列值。以下是数据库的第一行:
id product_name product_config detected_width created
1 Belt width 69.84 2020-04-19
2 Belt width 71.12 2020-04-19
在图选项卡中,我收到以下错误:错误:“数据”必须是向量类型,为“ NULL”所以,我猜列值没有被选中。任何人都可以帮忙吗?
library(pool)
library(dplyr)
library(shiny)
library(DBI)
library(plotly)
library(qcc)
ui <- fluidPage(
fluidRow(
column(4,
h3("Selecting Data"),
dateInput("date", "Enter a date:", value = Sys.Date())
),
column(8,
h3("Plot"),
tabsetPanel(
tabPanel("Table", tableOutput("tbl")),
tabPanel("Control Chart",plotOutput("plot"))
)
)
)
)
server <- function(input, output, session){
output$tbl <- renderTable({
conn <- dbConnect(
drv = RMySQL::MySQL(),
dbname = "testdatabase",
host = "localhost",
username = "root",
password = "root"
)
on.exit(dbDisconnect(conn), add = TRUE)
sql <- "SELECT * FROM Ceat_table WHERE created = ?date1;"
query <- sqlInterpolate(conn, sql, date1 = input$date)
dbGetQuery(conn, query)
})
output$plot <- renderPlot({
conn <- dbConnect(
drv = RMySQL::MySQL(),
dbname = "testdatabase",
host = "localhost",
username = "root",
password = "root"
)
on.exit(dbDisconnect(conn), add = TRUE)
sql <- "SELECT * FROM Ceat_table WHERE created = ?date1;"
query <- sqlInterpolate(conn, sql, date1 = input$date)
dbGetQuery(conn, query)
ceatdb <- tbl(conn, "Ceat_table")
a<-qcc(ceatdb$detected_width,type = "xbar.one")
plot(a)
})
}
shinyApp(ui = ui, server = server)
错误出在您的renderPlot
函数中。
注意,renderTable
功能中的最后一个命令是dbGetQuery(conn, query)
。这将从数据库中获取数据,由于这是最后一条命令,因此该命令的结果就是传递给UI的内容。
相反,对于renderPlot
功能,您可以通过两种不同的方式访问同一张表:
dbGetQuery(conn, query)
,但不将获取的结果存储在本地。ceatdb <- tbl(conn, "Ceat_table")
的远程表,但没有使用collect()
将结果完全加载到R中。我建议您仅使用以下一种方法。
dbGetQuery
的结果:conn <- dbConnect( your_connection_details_here )
on.exit(dbDisconnect(conn), add = TRUE)
sql <- "SELECT * FROM Ceat_table WHERE created = ?date1;"
query <- sqlInterpolate(conn, sql, date1 = input$date)
ceatdb = dbGetQuery(conn, query) # key change
a<-qcc(ceatdb$detected_width,type = "xbar.one")
plot(a)
collect()
将远程表加载到内存中:conn <- dbConnect( your_connection_details_here )
on.exit(dbDisconnect(conn), add = TRUE)
ceatdb <- tbl(conn, "Ceat_table") %>% collect() # key change
a<-qcc(ceatdb$detected_width,type = "xbar.one")
plot(a)
请注意,对于远程表,不能以与本地表相同的方式使用$
表示法访问列。一种证明这一点的方法是比较names(my_table)
和colnames(my_table)
的输出。本地表将为这两个命令提供相同的结果,而远程表则不会。