通过函数设置工作目录

时间:2014-04-16 10:40:20

标签: r function setwd

我是R的新手。我在通过一个函数设置我的工作目录时遇到了麻烦。 这就是我的尝试:

myfunction<-function(directory)
   {
     setwd(paste(getwd(),("/directory"))

   }

当我运行myfunction(“name”)时 它给出了错误:无法更改工作目录。

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

试试这个:

myfunction <- function(directory) setwd( file.path(getwd(), directory) )

或意识到getwd()是默认值,因此无需指定:

myfunction <- function(directory) setwd(directory)

或意识到你的函数实际上执行与setwd相同的功能,这将起作用:

myfunction <- setwd

答案 1 :(得分:1)

我不知道,但如果你有兴趣,这也可能有用:

https://github.com/imanojkumar/MyFunctions1/blob/master/README.md

或者只使用以下代码:

source("https://raw.githubusercontent.com/imanojkumar/MyFunctions1/master/ChangeDirectory.R")

上述源文件包含以下三个代码:

1。要求用户提供目录

的路径
directory <-  readline('Enter Path to Directory You want to set as
                        Default (use backslash e.g. "E:/MyDirectory") : ')
2.功能
myfunction <- function(directory) {
if (!is.null(directory))
   setwd(directory)
}

3。函数在后台运行,并将用户定义的目录设置为默认值

myfunction(directory)

答案 2 :(得分:0)

您面临的问题是使用&#34; /目录&#34;。如果您只使用目录而不是&#34;目录&#34; ,您将得到结果:如

  

myfunction&lt; - function(目录){
    setwd(目录)
  }

如果使用粘贴功能,输出将是一个字符串,最后它将被解释为将我的工作目录更改为&#34;目录&#34;这不存在,因此错误。 R增加了自己的&#34;&#34;因此你的函数变为setwd(&#34;&#34;目录&#34;&#34;)。你可以在path.expand()的帮助中阅读更多内容