2017-10-05 87 views
0

嗨給定的代碼使用代表字母和百分比列表的DT來生成基本表。我希望在DT表格中添加一個滑塊,以便當我將滑塊放置在特定百分比時,我會得到與該百分比及其以下相對應的行。謝謝,請幫助。實現動態滑塊來更新DT表百分比

## app.R ## 
library(shiny) 
library(shinydashboard) 
library(DT) 
library(scales) 
ui <- fluidPage(
titlePanel("Basic datatable"), 
# Create a new row for the table. 
fluidRow(
DT::dataTableOutput("table") 
) 
) 
server <- function(input, output) { 
# Filter data based on selections 
output$table <- DT::renderDataTable(DT::datatable({ 
a = percent(1:10) 
b = c("aa","bbb","cc","dd","ee","ff","gg","ff","gg","hh") 

data1 = data.frame(a,b) 
data1 

})) 
} 
shinyApp(ui, server) 

回答

0

這裏的實施sliderInput和動態地server改變datatable的方式。還有其他方法可以動態控制datatable,但我發佈此代碼以符合您的確切要求。

library(shiny) 
library(shinydashboard) 
library(DT) 

a <- percent(1:10) 
b <- c("aa","bbb","cc","dd","ee","ff","gg","ff","gg","hh") 
data1 <- data.frame(a,b) 
a_temp <- as.numeric(gsub("%|,", "", a))  #Removing % and , from the data frame 
data1_temp <- data.frame(a_temp,b)   #New data frame with integer values to reference row number required later 

if(interactive()){ 
    shinyApp(
    ui <- fluidPage(

     titlePanel("Basic datatable"), 

     sliderInput("slider1", "Choose Range of Percentage", 
        min = a_temp[1], 
        max = a_temp[10], 
        value = c(a_temp[1], a_temp[10]), 
        step = 100 
       ), 

     fluidRow(
     DT::dataTableOutput("table") 
    ) 
    ), 

    server = function(input, output){ 

     minRowVal <- reactive({ 
     which(grepl(input$slider1[[1]], data1_temp$a))  #Retrieve row number that matches selected range on sliderInput 
     }) 

     maxRowVal <- reactive({ 
     which(grepl(input$slider1[[2]], data1_temp$a))  #Retrieve row number that matches selected range on sliderInput 
     }) 

     observeEvent(input$slider1, { 
     output$table <- DT::renderDataTable({ 
      data1[minRowVal():maxRowVal(), ] 
     }) 
     }) 

    } 
) 
} 
+0

謝謝薩加爾,感謝您的幫助。 –

0

以下代碼從here改編而來。

library(DT) 

DT::datatable(
    data.frame(
    a = 1:10/100, 
    b = letters[1:10] 
), 
    filter = "top" 
) %>% formatPercentage('a') 
+0

非常感謝Gregor,非常有幫助。 –