R shiny写一个简单的功能

该博客介绍了如何使用R语言的Shiny库创建一个交互式应用,用户可以上传VCF文件,然后应用将计算并展示不同SNP(单核苷酸多态性)的数量分布图。通过ggplot2库生成的图形可以在PDF和PNG格式下保存,并提供下载按钮供用户下载。应用的核心功能是解析VCF文件,统计SNP频率,并利用histogram函数生成图表。
摘要由CSDN通过智能技术生成

初学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)
    
}


效果:
在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值