istudybrains
istudybrains

Reputation: 21

setwd error: directories within directories

Sorry this is long, but I'm a novice and want to be specific.

I have varied numbers of dataframes within a set of directories, within a set of directories. (That's 60 inner directories, hence I'm attempting to automate this.) My goal is to list and open each outer directory; within it, list and open each inner directory; and within that, perform some simple functions with the dataframes there (average some values, etc.).

The script returns "Error in setwd(inner) : cannot change working directory", and performs the function on files in the outer directory instead, only to the first outer directory. I think the script is calling the functions in the wrong order, perhaps it's because I nested for loops such that both setwd(inner) and setwd('..') are within setwd(outer) and setwd('..'), in order to access every directory in every directory. It's not a recursion or path-name issue, because the same error results whether recursive and full.names are TRUE or FALSE in my list of directories (with list.dirs).

I've read about the downfalls of using setwd, but I'm the only analyst and don't need to share the script with other people/machines/OSs (I use RStudio in Mac OS 10.7.5). Are there better functions than setwd for analyzing all files in each directory in each directory? Or do I need to use a simpler script to work only within an inner directory, and apply it by hand individually to those 60 directories? Thank you for reading and thank you in advance for any advice you can offer!

Upvotes: 2

Views: 388

Answers (1)

biobirdman
biobirdman

Reputation: 4120

I will use the function list.files function that ships with base r. list.files will searCH a folder recursively for files. You can also include a pattern so that the function only returns files that matches.

list.files will return the relative path to the files that you are looking for so you can read each dataframe without having to change your working directory.

I hope you will find this useful.

Let me know if you need any other help.

Cheers

Upvotes: 1

Related Questions