Store multiple outputs from each iteration of a for loop

旧巷老猫 提交于 2021-02-20 05:16:14

问题


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"

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

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

So, how can store multiple values (combinations) from each iteration in a for loop?

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"

回答1:


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



回答2:


You might try to set up a vector beforehand and then use this part in your for loop:

append(VectorName, pathFinal[i])

you might try to include it in your existing code like this

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

I haven't checked it, but it should add each new value to your desired vector. Also, I don't think you need to use setwd().



来源:https://stackoverflow.com/questions/40133110/store-multiple-outputs-from-each-iteration-of-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!