r - 从列表中获取计数数据后创建二进制矩阵文件
问题描述
在一个目录下,我有很多文本文件,文件的名称和格式如下:
SRS011061.txt
--------------------
contig SRS011061_idxstats.txt
BGC0000505 1
BGC0000505 1
SRS011090.txt
---------------------
contig SRS011090_idxstats.txt
BGC0000509 0
BGC0000509 1
SRS011271.txt
--------------------
contig SRS011271_idxstats.txt
BGC00001105 0
BGC00001105 0
从这些文件中,我想要两种类型的结果:
- 在每个文件中,当我们考虑不同的基因存在百分比(1/0 是存在和不存在)时,存在多少个基因(BGC**)。
对于这一步,我使用:
setwd("~/Desktop/test")
filenames <- list.files(full.names=F, pattern=".txt")
output <-lapply(filenames,function(i){
t<-read.csv(i, header=T, check.names = F, sep = " ")
t$gene_count<-1
t[,2][t[,2]>0]<-1
pre_abs<-aggregate(. ~ contig, t, sum)
colnames(pre_abs)<-c("BGC_Accession","Gene_presence", "Gene_count")
pre_abs$Percentage<-(pre_abs$Gene_presence/pre_abs$Gene_count)*100
gene_pre_100_percent<-length(pre_abs$Percentage[pre_abs$Percentage>=100])
gene_pre_20_percent<-length(pre_abs$Percentage[pre_abs$Percentage>=20])
data.frame(Combinations=i,gene_pre_100_percent=gene_pre_100_percent,gene_pre_20_percent=gene_pre_20_percent)
})
Step2_TP_FP<-do.call(rbind,output)
Step2_TP_FP[,1] <- data.frame(gsub(".txt.*$", "", Step2_TP_FP[,1]))
在这里,我得到的结果是,在 100% 和 20% 的基因完成情况下,每个文件中存在多少个基因。
Combinations gene_pre_100_percent gene_pre_20_percent
SRS011061 1 1
SRS011090 0 1
SRS011271 0 0
- 对于相同的百分比标准,我想制作一个二进制存在缺席矩阵。对于 100% 标准,矩阵应如下所示:
SRS011061 SRS011090 SRS011271
BGC0000505 1 0 0
BGC0000509 0 0 0
BGC00001105 0 0 0
对于 20% 的标准,它应该是:
SRS011061 SRS011090 SRS011271
BGC0000505 1 0 0
BGC0000509 0 1 0
BGC00001105 0 0 0
得到step1结果后如何创建这两个矩阵文件?谢谢!
解决方案
我认为,如果您保留所有信息并将存在率存储为百分比,而不是硬编码 20% 或 80%,然后一次性制作矩阵,这可能会更容易。例如对于一个文件,我们可以这样做:
output = lapply(fl,function(i){
x = read.table(i,header=TRUE)
cbind(aggregate(x[,2],list(gene=x[,1]),mean),
file=sub(".txt","",i)
)
})
output = do.call(rbind,output)
gene x file
1 BGC0000505 1.0 SRS011061
2 BGC0000509 0.5 SRS011090
3 BGC00001105 0.0 SRS011271
现在只需设置获取矩阵的截止值,然后将其更改为 50%、60%,无需再次读取文件:
matrixfunc = function(da,perc){
table(da$gene[da$x>perc],da$file[da$x>perc])
}
matrixfunc(output,0.8)
SRS011061 SRS011090 SRS011271
BGC0000505 1 0 0
BGC0000509 0 0 0
BGC00001105 0 0 0
matrixfunc(output,0.2)
SRS011061 SRS011090 SRS011271
BGC0000505 1 0 0
BGC0000509 0 1 0
BGC00001105 0 0 0
推荐阅读
- php - 没有为“x”防火墙上的“守卫”侦听器明确配置提供者是不明确的,因为有多个注册提供者
- vhdl - vhdl modelsim 向命令行返回“1”或“0”状态
- apache-spark - Apache Spark - 根据时间加载数据
- vba - 使用 VBA 或 AppleScript 在 Mac OS X 上获取 NetBIOS 名称
- android - 启用 proguard 后 webview 无法正常工作
- java - 库类的 JSON 蛇案例
- java - Spring Boot - 在事件发布时导致 bean 重新创建的原型范围
- authentication - 为什么我需要 OAuth2 密码授予流程的客户端 ID?
- flutter - 颤振导航弹出总是弹出到根目录
- c++ - 排序得到最大数