【R shiny】一些應用記錄
阿新 • • 發佈:2020-10-16
目錄
DT和downloadButton應用
library(shiny) library(DT) ui <- shinyUI( fluidPage( titlePanel("DT test"), downloadButton('downloadData', 'Download'), fluidRow( DT::dataTableOutput("table") ) ) ) server <- shinyServer(function(input, output) { output$table <- DT::renderDataTable(DT::datatable({ mtcars }, rownames = FALSE)) output$downloadData <- downloadHandler( filename = 'test.csv', content = function(file) { write.csv(mtcars, file) } ) }) shinyApp(ui,server)
downloadButton 中驗證結果輸出
一種情況是通過shinyjs,只有輸入時,才顯示下載按鈕:
library(shiny) ui <- fluidPage( shinyjs::useShinyjs(), textInput("text", "content", "", placeholder = "please insert something"), shinyjs::hidden(downloadButton("download")) ) server <- function(input, output, session) { output$download <- downloadHandler( filename = "file.csv", content = function(file) { write.csv(data.frame(content = input$text), file) } ) observeEvent(input$text, { if (input$text == "") shinyjs::hide("download") else shinyjs::show("download") }) } shinyApp(ui, server)
另一種情況是downloadButton搭配uiOutput,即只有輸出結果出現時,下載按鈕才出現。
#ui端
uiOutput("download")
#server端
output$download <- renderUI({
if(!is.null(input$file1) & !is.null(input$file2)) {
downloadButton('OutputFile', 'Download Output File')
}
})
新增進度條
但不是真正的程式進度。
# Only run examples in interactive R sessions
if (interactive()) {
options(device.ask.default = FALSE)
ui <- fluidPage(
plotOutput("plot")
)
server <- function(input, output) {
output$plot <- renderPlot({
withProgress(message = 'Calculation in progress',
detail = 'This may take a while...', value = 0, {
for (i in 1:15) {
incProgress(1/15)
Sys.sleep(0.25)
}
})
plot(cars)
})
}
shinyApp(ui, server)
}
如何確保僅在使用Shiny按下操作按鈕時才觸發操作
search_tweets <- function(search) return(search)
library(shiny)
ui <- fluidPage(
# Application title
#titlePanel("Twitter Analytics"),
fluidRow(
column( 4, titlePanel("Twitter Analytics")),
column( 3, textOutput("mysearch") ),
column( 4, textInput("searchstring",
label = "",
value = "")),
column(1,
br(),
actionButton("action", "go"))
)
)
server <- function(input, output) {
twitter <- eventReactive(input$action,{
search_tweets(input$searchstring)
})
output$mysearch <- renderText({
twitter()
})
}
shinyApp(ui, server)
其他
需要系統性學習了,不然不能隨心所欲,寸步難行。多看看別人的專案:
https://github.com/rli012/CancerMIRNome
https://github.com/wangshisheng/NAguideR