簡體   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