初学shiny,实现一个简单的功能:上传VCF文件,输出不同SNP数量图
shiny代码:
library(shiny) library(vcfR) library(tidyr) library(ggplot2) source("VCF.R") # Define UI ---- ui <- fluidPage( #titlePanel("title panel"), fluidRow( column(4,fileInput("counts", multiple = FALSE, accept = c(".vcf",".gz"), h3("Input your vcf file."))) ), fixedRow( column(4,actionButton("run", label = "Plot", icon = icon("paper-plane"))) ), hr(), fixedRow( column(1,downloadButton("downloadData", "Save PDF")), column(1,downloadButton("downloadData1", "Save PNG")), ), fixedRow( mainPanel(plotOutput("map")) ) ) # Define server logic ---- server <- function(input, output) { td <- getwd() options(shiny.maxRequestSize=100*1024^2) data <- reactive({ ## datapath is a must req(input$counts$datapath) }) observeEvent(input$run,{ output$map <- renderPlot({ #histogram('../mytest.vcf') histogram(data()) }) }) output$downloadData <- downloadHandler( filename = function() { paste("p1", "pdf", sep = ".") }, content = function(file) { file.copy(paste0(td,"/p1.pdf"), file) } ) output$downloadData1 <- downloadHandler( filename = function() { paste("p1", "png", sep = ".") }, content = function(file) { file.copy(paste0(td,"/p1.png"), file) } ) } # Run the app ---- shinyApp(ui = ui, server = server)
处理VCF文件脚本:
histogram <- function(var){ td <- getwd() con <- file(var, "r") line=readLines(con,n=1) table = data.frame( REF_ALT = c('AT','AG','AC','TG','TC','TA','GA','GT','GC','CA','CG','CT'), NUM = 0 ) while( length(line) != 0 ) { sta = startsWith(line, '#') if(sta == TRUE){ } else{ REF = c(strsplit(line, "t")[[1]][4]) ALT = c(strsplit(line, "t")[[1]][5]) table[which(table[,1]==paste0(REF,ALT)),2] <- table[which(table[,1]==paste0(REF,ALT)),2] + 1 } line=readLines(con,n=1) } p <- ggplot(table,aes(REF_ALT,NUM)) k <- p+geom_bar(stat = 'identity',aes(fill=NUM)) ggsave(paste0(td,"/p1.pdf"),plot = k,dpi=300) ggsave(paste0(td,"/p1.png"),plot = k,dpi=300) close(con) return(k) }
效果: