R 对某个文件夹下文件的批处理
R 是一个很不错的脚本语言,尤其是加入对正则表达式的支持(虽然跟perl 这类彪悍语言有差距,但是一般够用了)。之前做的项目要求把一个文件夹下的涉及某个群体的文件提取出来,当然,文件名就是这个群体的名称(正则表达式要大显神威啦),例如,我的文件夹是/home/fuopen/Desktop/pop/,我要找文件夹下所有文件名带有“CEU_"的“.csv"文件,这些文件当然是按照数字递增顺序编号的啦(这里是22个),并且提取一部分内容存入一个列表。怎么实现呢,代码
如下:
read_pp<-function(pop_dir){##pop_dir is the argument that accept pathname,e.g:/home/username/Desktop/test/
pd<-list.files(pop_dir); ##list.files read the names including in the folder and store the names in character array pd
fceu<-pd[which(grepl("CEU",pd))]; ## find filenames which contains "CEU" in pd
lceu<-as.numeric(unlist(strsplit(unlist(strsplit(fceu,"CEU_")),".csv")));##get file index which contains "CEU_"
ceu<-vector(mode="list",length=22);##vector whose elements are list, the length of the vector is 22
for(i in 1:22){
pceu<-paste(pop_dir,fceu[which(lceu==i)],sep=""); ##get the file name again by their nature order 1,2,3......
tmp<-read.csv(pceu);
ceu[i]<-list(i,chr_end,list(chr_cen[[1]],chr_cen[[2]]),list(tmp[[2]],tmp[[3]],tmp[[6]],tmp[[7]]));##read some columns in the file to the list
}
ceu; ##return to the vector
}
这样就ok了,当然想删除指定文件名的操作也可以用类似的代码,非常方便,删除文件的 命令是:unlink。
浙公网安备 33010602011771号