循环浏览R中的文件,并根据范围选择值

循环浏览R中的文件,并根据范围选择值,r,R,我有一个名为“基因”的文件,有4300行,看起来像 Gene_id chr start stop GeneA chr1 10 1000 GeneB chr1 2300 7000 GeneC chr1 10000 13577 Chr Bases chr1 160 chr1 157

我有一个名为“基因”的文件,有4300行,看起来像

Gene_id  chr  start   stop              
GeneA chr1  10  1000                 
GeneB chr1  2300  7000                     
GeneC chr1 10000 13577                
Chr Bases          
chr1 160           
chr1 157             
chr1 8500           
chr1 2200               
另一个文件名为“base”(约100000行),看起来像

Gene_id  chr  start   stop              
GeneA chr1  10  1000                 
GeneB chr1  2300  7000                     
GeneC chr1 10000 13577                
Chr Bases          
chr1 160           
chr1 157             
chr1 8500           
chr1 2200               
我想生成一个文件,使每个基因的碱基保持在起始和终止之间

所以输出看起来像

Chr Bases             
chr1 160            
chr1 157                
我已经尝试过此功能,但它只返回第一个条目四次:

methC <- apply(bases,1,function(a){
my_bases <- bases[bases[1]==genes$chr & bases[2]>=genes$start & bases[2]<=genes$stop,]
result <- my_bases[,2]
return(result)
})

>methC
# 160 160 160
methcb
氯基
(或长度为0的行名称)

,这就是为什么我认为函数更适合处理大型数据集。

我会使用数据表库:

library("data.table")

# Read the data from file
genes <- data.table(read.csv("genes.csv"))
bases <- data.table(read.csv("bases.csv"))

# Define the columns that are used to join the two tables
setkey(genes, chr)
setkey(bases, Chr)

# The first line joins the two tables, and the second line
# filters the result to keep only those that match and defines
# the columns that are to be shown in the output. Note the need
# to take care with capitalisation and the reserved word 'stop'
genes[bases, allow.cartesian = TRUE][
  Bases >= start & Bases <= `stop`, list(Chr = chr, Bases)]
可能是此链接有帮助,也可能是:您可以使用
fread()
读取文件。和
foverlaps()
执行重叠范围联接。
    Chr Bases
1: chr1   160
2: chr1   157