2015-02-07 82 views
1

我有一個目錄這是相同實驗的重複約150個文件,但它們之間變化的行匹配目錄中的所有文件之間的所有行

的數量方面他們都具有以下格式

Chr,Bases   
chr1,189   
chr1,1465    
chr1,7845   
chr1,12844 

我想保留出現在每個文件中的「基礎」,因此任何特定文件的行也存在於每個其他文件中。 我認爲這樣做是採取與行數最少的文件最簡單的方法,並用它來在其它文件

library(data.table) 
#get smallest file 
smallest.file <- data.table(read.table='smallest_file.txt', header=T, sep=',') 
setkey(smallest.file, Bases) 
#get others 
other.files <- list.files(pattern="*.bed", full.names=T) 

#function to match Bases between those in the smallest file 
#and the others 
match_bases <- function (i) { 
others <- data.table(read.table(i, header=T, sep=',')) 
setkey(others, Bases) 
match_result <- smallest.file[others, allow.cartesian=TRUE] [ 
Bases==Bases, list(Chr=Chr, Bases)] 
#write results to a new file 
this_file <- paste0(i, ".csv") 
write.table(bases, file=this_file, sep=',', row.names=F, quote=F) 
} 


sapply(other.files, match_bases) #preform function for each file 

這似乎工作相匹配的行。

但是我意識到後,我有一個問題,缺少的行是隨機的,所以'最小的文件'中的一些行也是該文件唯一的,而其他行中沒有看到。

所以我覺得第二個方法我可以使用將合併的所有文件,並保持被重複150次行

我看着duplicated()功能來做到這一點(他們被看見在每個文件) ,但我不認爲這是可能的。我認爲它可能不是最有效的方式。

回答

2

也許這可以工作,這個想法是使用所有= T,使NAS會如果值是缺少被添加到合併所有的數據幀,並刪除具有NA任何行:

library(data.table) 
#get the files 
files<- list.files(".", pattern="*.txt") 

#read them in a list 
data <- lapply(files, function(x){fread(x,header=T,sep=",")}) 
#rename the Chr colum to Chr_nameoffile 
mapply(function(x,y){setnames(y,c(paste("Chr_",x,sep=""),"Bases"))},files,data) 



#merge all the data frames 
mergedData<-Reduce(function(...) merge(...,all=T,by="Bases"),data) 

#Take only those without NAs 
mergedData<-mergedData[apply(mergedData,1,function(x){sum(is.na(x))==0}),] 

#split the data frame into files of the correct name, using the Chr_nameoffile column 
for (i in 2:ncol(mergedData)){ 
     fileToWrite<-paste("new",unlist(strsplit(colnames(mergedData[,c(1,i),with=F])[2],"_"))[2],sep="_") 
     write.table(mergedData[,c(i,1),with=F], file=fileToWrite, sep=',', row.names=F, quote=F) 
} 
+0

非常好主意,只是試了一下。不幸的是,我的文件非常大,R告訴我它「無法分配大小爲4.4Gb的矢量」 – user3816990 2015-02-08 19:33:18

+1

我不知道你是否熟悉bash或python,但是如果你是''multijoin'腳本[here] ://github.com/agordon/bin_scripts)可以做同樣的事情(它根據列連接多個文件,並且如果某些文件沒有一行,可以設置'填充符') – NicE 2015-02-08 19:39:31

+0

謝謝建議,我會研究一下 – user3816990 2015-02-08 19:53:19