本文介绍了存储for循环的每次迭代的多个输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出每年的修复路径和非常有限的目录.我正在尝试获取此初始组合( fixPath-年)和每个组合中包含的不同的非固定数量和非相等数量子目录之间的路径的每种组合 fixPath-年

Given a fix path and a very limited directories from year. I'm trying to obtain each combination of path between this initial combination (fixPath - year) and the different, non-fixed and non-equally quantity, subdirectories contained in each combination of fixPath - year

fixPath <- "C:/Users/calcazar/Desktop/example"
year <- 2008:2010
pathVector <- paste(fixPath, year, sep = "/")
pathVector
[1] "C:/Users/calcazar/Desktop/example/2008" "C:/Users/calcazar/Desktop/example/2009"
[3] "C:/Users/calcazar/Desktop/example/2010"

我解决此问题的方法是使用for循环:

My approach to solve this problem is use a for-loop:

  1. 使用 setwd(pathVector [1])
  2. 设置工作目录
  3. 使用该工作目录中的 list.files 扫描文件(子目录),并通过以下方式获得每个组合: paste(pathVector [1],list.files(pathVector [1]),sep ="/")
  4. 将此组合存储在向量中,然后进行下一个迭代
  1. Set the working directory with setwd(pathVector[1])
  2. Scan the files (the subdirectories) with list.filesin that working directory and obtain each combination with: paste(pathVector[1], list.files(pathVector[1]), sep = "/")
  3. Store this combinations in a vector and proceed with the next iteration

...但是在循环的每次迭代中,我都有很多组合,但我不知道如何为每次迭代存储多个.这是我的代码:

...but from each iteration of the loop I have a bunch of combinations and I can't figure out how to store more than one for each iteration. Here is my code:

for (i in seq_along(pathVector)) {
setwd(pathVector[i])
# here I only obtain the combination of the last iteration
# and if I use pathFinal[i] I only obtain the first combination of each iteration
pathFinal <- paste(pathVector[i], list.files(pathVector[i]), sep = "/")
# print give me all the combinations
print(pathFinal[i])
}

那么,如何将每个迭代中的多个值(组合)存储在for循环中?

我想要一个包含所有组合的向量,例如:

I want a vector that contain all the combinations, for example:

 "C:/Users/calcazar/Desktop/example/2008/a"
 "C:/Users/calcazar/Desktop/example/2008/z"
 "C:/Users/calcazar/Desktop/example/2009/b"
 "C:/Users/calcazar/Desktop/example/2009/z"
 "C:/Users/calcazar/Desktop/example/2009/y"
 "C:/Users/calcazar/Desktop/example/2010/u"

推荐答案

这样的事情会做你想要的吗?

Would something like this do what you want?

pathFinal = NULL

for (i in seq_along(pathVector)) {
  setwd(pathVector[i])

  pathFinal <- c(pathFinal, paste(pathVector[i], list.files(pathVector[i]), sep = "/"))

  print(pathFinal[i])
}

这篇关于存储for循环的每次迭代的多个输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:20