使用索引遍历矢量的子集 [英] Iterate over a subset of a vector using indices

查看:130
本文介绍了使用索引遍历矢量的子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以遍历目录中的所有文件。但是,我想遍历某些文件,而不是所有的文件。我想要使​​用索引。

我想通过使用 file_id 向量来做到这一点。每个向量元素都是文件中的索引。

例如:我在一个目录中有500个文件,我只想迭代三个文件,即文件2 ,4,15。我生成了一个名为 file_id = c(2,4,15)的向量。现在,我如何迭代只有这些文件或索引,如文件[2] 文件[4] files [15] 这将只从文件2,4和15中获取数据,而不是所有的500个文件。

 #获取目录中所有文件的列表。 
files< - list.files(directory,full.names = TRUE)

#iterate目录中的所有文件,并获取文件数据
for(item in files ){
filedata< - read.csv(item)
}

我想要做的只是遍历file_id向量中指定的以下文件。这将打开文件2,4和15没有别的。
file_id = c(2,4,31)


解决方案

 <$ c $ 在循环中对进行迭代时, c> for(index in SET)

其中 index 是你的迭代器, SET是任何可以转换为向量的东西(甚至是一个矩阵或数组,它将遍历每个元素)。 b
$ b

 #获取目录中所有文件的列表。 
files< - list.files(directory,full.names = TRUE)

file_id = c(2,4,31)

#iterate over all (file_id){
filedata< - read.csv(files [i])
}
$ c>

在这里,您只需要修改 file_id 来循环指定文件。 / p>

I can iterate over all the files in a directory. However, I want to iterate over certain files instead of all the files. I want to use indices.

I want to do this by using a file_id vector. Each vector element would be index in "files".

For example: I have 500 total files in a directory, and I only want to iterate three files which are files 2,4,15. I generated a vector called file_id = c(2, 4, 15). Now, how can I iterate over only these files or indices, such as files[2], files[4], files[15] which will get data only from files 2, 4, and 15, instead of all 500 files.

#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)

解决方案

When you iterate inside a for loop, the syntax is:

for(index in SET) 

where index is your iterator and SET is anything that can be converted to a vector (even a matrix or array, it'll loop over each element).

#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])
}

here, you only need to modify file_id to loop over that specific files.

这篇关于使用索引遍历矢量的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆