【问题标题】:Store multiple outputs from each iteration of a for loop存储来自 for 循环的每次迭代的多个输出
【发布时间】:2016-10-19 13:41:59
【问题描述】:

给定一个修复路径和一年以来非常有限的目录。我正在尝试获取此初始组合 (fixPath - year) 和不同的、非固定和非等量子目录之间的路径组合fixPath - 年份的组合

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循环:

  1. setwd(pathVector[1])设置工作目录
  2. 在该工作目录中扫描带有list.files 的文件(子目录),并获得每个组合:paste(pathVector[1], list.files(pathVector[1]), sep = "/")
  3. 将此组合存储在向量中并继续下一次迭代

...但是在循环的每次迭代中我都有一堆组合,我无法弄清楚如何为每次迭代存储多个组合。这是我的代码:

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 循环中存储每次迭代的多个值(组合)?

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

 "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"

【问题讨论】:

  • list.files(full.names = TRUE, recursive = TRUE) 对这项任务有帮助吗?
  • 不,它不起作用。关于如何应用full.names = TRUErecursive = TRUE 的任何建议?因为它不适用于list.files(fixPath, full.names = TRUE, recursive = TRUE)
  • list.files(fixPath, recursive = TRUE, include.dirs = TRUE) 完美!

标签: r for-loop filepath


【解决方案1】:

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

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

【讨论】:

  • 赋值运算符“c”完成了所有组合的封装工作,但打印函数只显示第一次迭代的组合。顺便谢谢你的回答!
  • 好的,我们已经完成了一半! :) 您想在每次迭代中打印所有子目录吗?因为您可以只打印 paste 参数 (paste(pathVector[i], list.files(pathVector[i]), sep = "/") )。或者您想要一个包含每次迭代的所有子目录的列表?
【解决方案2】:

您可以尝试预先设置一个向量,然后在您的 for 循环中使用这部分:

append(VectorName, pathFinal[i])

您可以尝试像这样将它包含在您现有的代码中

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

我还没有检查它,但它应该将每个新值添加到您想要的向量中。另外,我认为您不需要使用setwd()

【讨论】:

  • 或使用foreach 库。
  • append 函数负责封装每次迭代中的所有组合。你是对的,使用“setwd”是多余的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多