繁体   English   中英

R Shiny:从SQL查询格式化反应性data.frame

[英]R Shiny: Formatting reactive data.frame from sql query

我试图弄清楚如何从反应式SQL查询中获取数据后更改列的类型...

例如,当我从数据库中获取数据时,某些列是字符,我希望它们成为因素。 而且有些列是数字的(这是正确的),但我需要将它们显示为数据表中的因子(供数据表使用,因为命名为Tolerance的列,并且不能按范围过滤公差,所以它应该是一个数)。

简单的代码:

library(ROracle)
library(shiny)
library(DT)


server <- shinyServer(
  function(input, output, session) {

    con <- dbConnect(dbDriver("Oracle"),"xx/K",username="user",password="pwd")
    tableList <- dbListTables(con,schema="K")

    updateSelectizeInput(session, "tabnames", server = TRUE, choices = tableList)

      sqlOutput <- reactive({
        sqlInput <- paste("select rownum * from K.",input$tabnames)
        dbGetQuery(con$cc, sqlInput, stringsAsFactors = T)#it hasnt worked neither
      })

    output$table <- DT::renderDataTable(sqlOutput(), server=TRUE, rownames=TRUE, filter="top", options=list(pageLength=10))

    session$onSessionEnded(function() { dbDisconnect(con) })
  })

ui_panel <- 
  tabPanel("Test",
           sidebarLayout(
             sidebarPanel( 
             ),
             mainPanel(
               selectizeInput("tabnames",label = "server side", choices = NULL),

               tableOutput("out"),
               tableOutput("table")
             )
           )
  )


ui <- shinyUI(navbarPage("Test",ui_panel))

runApp(list(ui=ui,server=server))

当我尝试简单地:

output$table <- DT::renderDataTable({

sqlOutput()$HOEHE_TOLP <- as.factor(sqlOutput()$HOEHE_TOLP)

datatable(sqlOutput(), server=TRUE, rownames=TRUE, filter="top", options=list(pageLength=10))})

它没有用,给了我一个错误:

Error in sqlOutput()$HOEHE_TOLP <- as.factor(sqlOutput()$HOEHE_TOLP) : 
  ungültige (NULL) linke Seite in Zuweisung

* invalid (NULL) left side of assignment

任何想法如何将某些列转换为反应数据帧的因子?

干杯

编辑:

只需替换此表达式:

output$table <- DT::renderDataTable(sqlOutput(), server=TRUE, 
  rownames=TRUE, filter="top", options=list(pageLength=10))

带有:

output$table <- DT::renderDataTable({
  intermed <- sqlOutput()
  intermed$HOEHE_TOLP <- as.factor(intermed$HOEHE_TOLP)
  datatable(intermed) %>% formatStyle("RUND2_MITT", color = 'red', 
    backgroundColor = 'lightyellow', fontWeight = 'bold')
}, server=TRUE, rownames=TRUE, filter="top", options=list(pageLength=10))

这是一个自包含的示例:

library(DT)
library(shiny)

ui <- fluidPage(
  actionButton("inst", "Instigate Reactive"),
  dataTableOutput("test")
)

server <- function(input, output){
  data <- eventReactive(input$inst, {
    iris
  })

  output$test <- renderDataTable({
    set <- data()
    set$Sepal.Length <- as.factor(set$Sepal.Length)
    datatable(set) %>% formatStyle("Petal.Length", color = 'red', 
                                   backgroundColor = 'lightyellow',
                                   fontWeight = 'bold')
  })
}

shinyApp(ui, server)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM