R set the working directory to the folder

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

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

instead he prints

 C:/Users/Blah/Desktop/dir2 

But when I run dirs in the console, I get:

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

as 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 
0
r
source share
2 answers

Have you checked the optional arguments to 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 a "path", so your temp function will be applied first with the directory you pass list.dirs (), "C: / Users / Blah / Desktop / dir2", you can try using list.dirs ("C: / Users / Blah / Desktop / dir2", recursive = FALSE) (if everything is ok with what you want)

0
source share

Your question is quite difficult to fulfill.

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

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

You can try using full.names = TRUE in the .dirs list, in which your temp function returns the working directory to its original state

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

An even better idea is, instead of messing around with the working directory, just pass the appropriate xmlParse file xmlParse (or whatever your function does)

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

All Articles