繁体   English   中英

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

[英]R set working directory to folder

我正在尝试将工作目录设置为函数中的其他子文件夹。 我希望print命令能够打印出来

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

相反它打印

C:/Users/Blah/Desktop/dir2

然而,当我在控制台中运行dirs时,我得到:

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

像我预期的那样。 这是我的代码:

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

你的问题很难理解。

list.dirs将返回(默认情况下)相对于当前工作目录的路径。

如果更改工作目录,则相对路径将无效。

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

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

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

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

你检查过list.dirs()的可选参数吗? https://stat.ethz.ch/R-manual/R-devel/library/base/html/list.files.html

文档说默认情况下,答案包含“path”本身,因此你的函数temp将首先应用于你给list.dirs(),“C:/ Users / Blah / Desktop / dir2”的目录。 您可能想尝试使用list.dirs(“C:/ Users / Blah / Desktop / dir2”,递归= FALSE)(如果你想要的话可​​以)

暂无
暂无

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

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