循环浏览R目录中的所有文件 [英] Looping through all files in a directory in R
问题描述
这是我第一次使用R,我只需要输入一个包含一些文件的包并将输出保存在其他文件中.我有一个目录,其中有一些带有".pdb"文件扩展名的文件.我需要在for循环中遍历每个文件,应用一些函数,并将每个矩阵的输出保存在一个文件中,以便以后在Matlab中使用.
It's my first time using R, and I just need to input a package with some files and save the outputs in some other files. I have a directory in which there are some files with ".pdb" file extensions. I need to go through each of these files in a for loop, apply some functions, and save the output of each ,which is a matrix, in a file that I could later use in Matlab.
这些是我希望应用于每个.pdb文件的功能.
These are the functions that I wish to apply to each of the .pdb files.
p=extractPDB("1HXH.pdb")
cm<-build.contacts(n=p$lca,xyz=p$coords,cuts=169)$cm
cm是我要保存在文件中的输出矩阵,以便以后在Matlab中使用.
cm is the output matrix which I want to save in a file to be later used in Matlab.
推荐答案
轻松浏览具有特定扩展名的文件.实际上,您遍历了文件名.
Looping over files with a certain extension is easy. Actually you loop over the filenames.
- 获取目录中所有文件的列表
- 仅获取以pdb结尾的文件
- 在名称上循环
您可能必须使用setwd
all.files <- list.files()
my.files <- grep(".*pdb", all_files, value=T)
for(i in my_files){
# do your operations here
p=extractPDB("1HXH.pdb")
cm<-build.contacts(n=p$lca,xyz=p$coords,cuts=169)$cm
# save
output.filename <- gsub("(.*?).pdb", "\\1.csv", i)
write.table(cm, output.filename)
}
要保存文件,有很多选项,要在matlab中读取文件,最好将矩阵另存为csv文件.查看write.table
的文档并调整参数,以方便阅读.
For saving the Files there are many options, for reading the file in matlab it's probably the best to save the matrices as csv-file. Look into the documentation of write.table
and adjust the parameters so it's convinient for reading.
这篇关于循环浏览R目录中的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!