0
votes

I am trying to set the working directory to a different subfolder in a function. I expected the print command to print

C:/Users/Blah/Desktop/dir2/SUBFOLDER 

instead it prints

C:/Users/Blah/Desktop/dir2

Yet when I run dirs in console I get:

C:/Users/Blah/Desktop/dir2/SUBFOLDER 
...(Much longer list)

like I expected. Here is my code:

temp<-function(path)
{
  print(path) #output is C:/Users/Blah/Desktop/dir2
  setwd(path)
  print(getwd())
  xml=xmlParse("filename.xml")
  ...
}

dirs<-list.dirs("C:/Users/Blah/Desktop/dir2")
lapply(dirs,temp)#apply function tempt to every item in dirs
2
I guess the first directory is the root directory you specified. What about lapply(dirs[-1],temp)?lukeA
I don't know exactly what you see as output, but the first element of the vector (after running dirs<-list.dirs("C:/Users/Blah/Desktop/dir2") is the current directory i.e. in your case "C:/Users/Blah/Desktop/dir2". So, this is the one that would be printed first by your function (and then all the subfolders). At least this is the normal behaviour.LyzandeR

2 Answers

0
votes

Have you checked the optional arguments of list.dirs() ? (https://stat.ethz.ch/R-manual/R-devel/library/base/html/list.files.html)

The documentation says that by default, the answer includes "path" itself, so your function temp will first be applied with the directory you give to list.dirs(), "C:/Users/Blah/Desktop/dir2". You may want to try with list.dirs("C:/Users/Blah/Desktop/dir2", recursive = FALSE) (if it's ok with what you want)

0
votes

Your question is rather difficult to follow.

list.dirs will return (by default) the paths relative to the current working directory.

If you change the working directory, then the relative paths will not be valid.

You could try using full.names = TRUE within list.dirs having your temp function return the working directory to it's original state

temp <- function(path) {
           owd <- getwd()
           on.exit(setwd(owd))
           print(path) 
           setwd(path)
         print(getwd())
    }

An even better idea might be to, instead of messing with the working directory, simply pass the appropriate file name to xmlParse (or whatever your function is doing)

files <- list.files(pattern = '\\.xml$', recurvise = TRUE)
XML <-   lapply(files, xmlParse)