[R] repeating functions for different folders?

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Fri Apr 13 07:11:22 CEST 2018


Hello,

Inline.

On 4/13/2018 1:10 AM, Jim Lemon wrote:
> Hi Marna,
> Assuming that you are descending into different subdirectories from
> the same directory:

Maybe this assumption is not needed.
Since setwd returns the current directory, it is safer to assign that 
value to a variable and in the end use it reset the original state.

> 
> directories<-c("dir1","dir2","dir3")
> for(directory in directories) {
>   setwd(directory)
>   # do whatever you want to do
>   # then return to the directory above
>   setwd("..")
> }

Using your code,

directories<-c("dir1","dir2","dir3")
for(directory in directories) {
    old_dir <- setwd(directory)
    # do whatever you want to do
    # then return to the original directory
    setwd(old_dir)
}


Hope this helps,

Rui Barradas

> 
> This will allow you to start and finish in the same directory.
> 
> Jim
> 
> 
> On Fri, Apr 13, 2018 at 9:47 AM, Marna Wagley <marna.wagley using gmail.com> wrote:
>> Hi R users,
>> I need to run a analysis using a data for each folder. I do have several
>> folders. Each folder contains several files but these files name are
>> similar to the files that is saved into  another folders.  I need to repeat
>> the analysis for every folder and would like to save the output in that
>> particular folder.  After completing the analysis in one folder, I want to
>> move another folder. Basically I was doing manually (repeating the analysis
>> each and every folder manually). Is there any way to make a loop so that I
>> can run the analysis for different folders? Is there any example code?
>>
>> Thanks for your help.
>> MW
>>
>>          [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list