问题
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:
- Set the working directory with
setwd(pathVector[1])
- Scan the files (the subdirectories) with
list.files
in that working directory and obtain each combination with:paste(pathVector[1], list.files(pathVector[1]), sep = "/")
- 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