2017-04-06 124 views
6

我试图与列的“N”数字显示数据表如下图所示创建R中深入报表闪亮

Begin Date | EndDate | Month | Year | Count of Students 
2/1/2014 | 1/31/2015 | Jan | 2014 | 10 
3/1/2014 | 2/28/2015 | Feb | 2014 | 20 
4/1/2014 | 3/31/2015 | Mar | 2014 | 30 
5/1/2014 | 4/30/2015 | Apr | 2014 | 40 

我想使这个数据表互动通过启用向下钻取/钻头通过功能,用户可以单击“学生计数”字段中的每个值来查看这些数字10,20,30和40后面的基础原始数据。 例如,如果用户单击“10 “,他/她应该能够看到数据背后的学生原始数据。这与Excel中的Pivot表概念类似,用户可以在其中查看Pivot表背后的基础数据。有没有办法使用R Shiny做同样的事情?

+0

两件事情:应该如何钻取存在于用户界面;你是如何将数据输入表格的?你必须创建一个ui的经验,用闪亮的句柄来处理下钻,以及一种处理数据的方法,将点击'10'的数据连接到可以从该列中的子集'10'的数据框。 –

回答

7

是的,使用DT包捕获选定的行和子集主集。下面是使用iris树立了榜样:

library("dplyr") 
library("shiny") 
library("DT") 

# create a summary table 
summary_iris <- group_by(iris, Species) %>% 
    summarise(Count = n()) 

ui <- fluidPage(
    dataTableOutput("summary") 
    , dataTableOutput("drilldown") 
) 


server <- function(input, output){ 

    # display the data that is available to be drilled down 
    output$summary <- DT::renderDataTable(summary_iris) 

    # subset the records to the row that was clicked 
    drilldata <- reactive({ 
    shiny::validate(
     need(length(input$summary_rows_selected) > 0, "Select rows to drill down!") 
    )  

    # subset the summary table and extract the column to subset on 
    # if you have more than one column, consider a merge instead 
    # NOTE: the selected row indices will be character type so they 
    # must be converted to numeric or integer before subsetting 
    selected_species <- summary_iris[as.integer(input$summary_rows_selected), ]$Species 
    iris[iris$Species %in% selected_species, ] 
    }) 

    # display the subsetted data 
    output$drilldown <- DT::renderDataTable(drilldata()) 
} 

shinyApp(ui, server) 

enter image description here

+0

R如何知道输入$ summary_rows_selected是什么?由于inputid summary_rows_selected中的任何内容都没有在代码中定义,而是直接调用。 – Digvijay

+0

没关系得到它! 如果其他人有同样的问题,**输入$ tableId_rows_selected **是DT中的预定义函数。 https://rstudio.github.io/DT/shiny.html – Digvijay