gpt4 book ai didi

r - 如何在R中读取vcf文件

转载 作者:行者123 更新时间:2023-12-04 17:46:37 71 4
gpt4 key购买 nike

我有这个 VCF format file ,我想在 R 中读取这个文件。但是,这个文件包含一些我想跳过的冗余行。我想在结果中得到类似的结果,该行以匹配 #CHROM 的行开头.

这是我尝试过的:

chromo1<-try(scan(myfile.vcf,what=character(),n=5000,sep="\n",skip=0,fill=TRUE,na.strings="",quote="\"")) ## find the start of the vcf file
skip.lines<-grep("^#CHROM",chromo1)


column.labels<-read.delim(myfile.vcf,header=F,nrows=1,skip=(skip.lines-1),sep="\t",fill=TRUE,stringsAsFactors=FALSE,na.strings="",quote="\"")
num.vars<-dim(column.labels)[2]

我的文件.vcf
    #not wanted line
#unnecessary line
#junk line
#CHROM POS ID REF ALT
11 33443 3 A T
12 33445 5 A G

结果
    #CHROM  POS     ID      REF     ALT
11 33443 3 A T
12 33445 5 A G

最佳答案

也许这对你有好处:

# read two times the vcf file, first for the columns names, second for the data
tmp_vcf<-readLines("test.vcf")
tmp_vcf_data<-read.table("test.vcf", stringsAsFactors = FALSE)

# filter for the columns names
tmp_vcf<-tmp_vcf[-(grep("#CHROM",tmp_vcf)+1):-(length(tmp_vcf))]
vcf_names<-unlist(strsplit(tmp_vcf[length(tmp_vcf)],"\t"))
names(tmp_vcf_data)<-vcf_names

ps:如果您有多个 vcf 文件,那么您应该使用 lapply 功能。

最好的事物,
罗伯特

关于r - 如何在R中读取vcf文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32513776/

71 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com