简体   繁体   English

R将工作目录设置为文件夹

[英]R set working directory to folder

I am trying to set the working directory to a different subfolder in a function. 我正在尝试将工作目录设置为函数中的其他子文件夹。 I expected the print command to print 我希望print命令能够打印出来

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

instead it prints 相反它打印

C:/Users/Blah/Desktop/dir2

Yet when I run dirs in console I get: 然而,当我在控制台中运行dirs时,我得到:

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

Your question is rather difficult to follow. 你的问题很难理解。

list.dirs will return (by default) the paths relative to the current working directory. list.dirs将返回(默认情况下)相对于当前工作目录的路径。

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 您可以尝试在list.dirs中使用full.names = TRUE ,使您的temp函数将工作目录返回到其原始状态

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) 更好的想法可能是,而不是弄乱工作目录,只需将适当的文件名传递给xmlParse (或您的函数正在做的任何事情)

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

Have you checked the optional arguments of list.dirs() ? 你检查过list.dirs()的可选参数吗? ( https://stat.ethz.ch/R-manual/R-devel/library/base/html/list.files.html ) 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". 文档说默认情况下,答案包含“path”本身,因此你的函数temp将首先应用于你给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) 您可能想尝试使用list.dirs(“C:/ Users / Blah / Desktop / dir2”,递归= FALSE)(如果你想要的话可​​以)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM