[英]How to render Datatable using DT in R shiny
我正在开发一个 R shiny 应用程序,它读取 many.xpt 文件并在表格中显示数据。 用户还可以通过选择“selectInput”选项来选择要显示的文件。
我在这里使用 DT 来渲染数据表,以便默认显示过滤框。 遗憾的是,未呈现 DataTable。 我无法弄清楚这个问题。
还有一个帮助:因为我是 R shiny 的新手,所以我无法弄清楚我的数据表(在哪个变量上,也许是“df”)保存在哪里,以便我可以在将来使用它来添加额外的功能。
数据:
垫.xpt:
STUDYID DOMAIN SUBID MATSEQ
1 Mat Mat_1 1
2 Mat Mat_2 2
3 Mat Mat_3 3
4 Mat Mat_4 4
5 Mat Mat_5 5
6 Mat Mat_6 6
7 Mat Mat_7 7
Cap.xpt
STUDYID DOMAIN SUBID MATSEQ
1 Cap Cap_1 1
2 Cap Cap_2 2
3 Cap Cap_3 3
4 Cap Cap_4 4
5 Cap Cap_5 5
6 Cap Cap_6 6
7 Cap Cap_7 7
代码
library(shiny)
library(haven)
library(stringr)
library(DT)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File",
multiple = TRUE,
accept = c(
"text/csv",
"text/comma-separated-values,text/plain",
".csv", ".xpt"
)
),
tags$hr(),
checkboxInput("header", "Header", TRUE),
dataTableOutput("files_available")
),
mainPanel(
tableOutput("contents")
)
)
)
server <- function(input, output) {
output$files_available <- renderUI({
req(input$file1)
selectInput("name", str_to_title("select which file to show"), choices = input$file1$name)
})
df <- reactive({
req(input$name)
read_xpt(input$file1$datapath[[which(input$file1$name == input$name)]])
})
output$files_available <- renderDataTable({
datatable(df(), filter="top",options = list(lengthChange = FALSE),callback=JS("
//hide column filters for the first two columns
$.each([0, 1], function(i, v) {
$('input.form-control').eq(v).hide()
});"))})
}
shinyApp(ui, server)
由于您没有指定csv
文件,我假设xpt
文件列在name
列中。 在那种情况下,以下应该起作用。
library(shiny)
library(haven)
library(stringr)
library(DT)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
fileInput("file1", "Choose CSV File",
multiple = TRUE,
accept = c(
"text/csv",
"text/comma-separated-values,text/plain",
".csv"
)
),
tags$hr(),
checkboxInput("header", "Header", TRUE),
uiOutput("files_available")
),
mainPanel(
DTOutput("contents")
)
)
)
server <- function(input, output) {
fdf <- reactive({
if (is.null(input$file1)){return(NULL)}
inFile <- input$file1
read.csv(inFile$datapath, header = input$header)
})
output$files_available <- renderUI({
req(fdf())
selectInput("name", str_to_title("select which file to show"), choices = fdf()$name)
})
df <- reactive({
req(input$name)
read_xpt(input$name)
})
output$contents <- renderDT({
datatable(df(), filter="top",options = list(lengthChange = FALSE) )
})
### delete search in the first two columns
# output$contents <- renderDT({
# datatable(df(), filter="top",options = list(lengthChange = FALSE),callback=JS("
# //hide column filters for the first two columns
# $.each([0, 1], function(i, v) {
# $('input.form-control').eq(v).hide()
# });"))
# })
}
shinyApp(ui, server)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.