我可以遍历目录中的所有文件。但是,我想迭代某些文件而不是所有文件。我想使用索引。
我想通过使用来做到这一点file_id
向量。每个向量元素将是“文件”中的索引。
例如:我在一个目录中有 500 个文件,我只想迭代三个文件,即文件 2、4、15。我生成了一个名为file_id = c(2, 4, 15)
。现在,我如何仅迭代这些文件或索引,例如files[2]
, files[4]
, files[15]
它将仅从文件 2、4 和 15 获取数据,而不是所有 500 个文件。
#get a list of all the files in directory.
files <- list.files(directory, full.names = TRUE)
#iterate over all the files in directory, and get file data
for (item in files){
filedata <- read.csv(item)
}
#What I want to do is only iterate over following files indicated in file_id vector. That will open files 2,4, and 15 nothing else.
file_id = c(2, 4, 31)
当你在一个内部迭代时for
循环,语法为:
for(index in SET)
where index
是你的迭代器并且SET
是任何可以转换为向量的东西(即使是矩阵或数组,它也会循环每个元素)。
#get a list of all the files in directory.
files <- list.files(directory, full.names = TRUE)
file_id = c(2, 4, 31)
#iterate over all the files in directory, and get file data
for (i in file_id){
filedata <- read.csv(files[i])
}
这里,你只需要修改file_id
循环遍历该特定文件。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)