4

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

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

   }

当我运行 myfunction("name") 时出现错误:无法更改工作目录。

提前感谢您的帮助。

4

3 回答 3

2

尝试这个:

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

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

myfunction <- function(directory) setwd(directory)

或意识到您的函数实际上执行与setwd此相同的功能:

myfunction <- setwd
于 2014-04-16T11:11:43.400 回答
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)
于 2016-03-29T06:59:25.750 回答
0

您面临的问题是使用“/目录”。如果您只使用目录而不是“目录” ,您将获得结果,如下所示:

我的函数 <- 函数(目录){
setwd(目录)
}

如果您使用粘贴功能,输出将是一个字符串,最后它会被解释为将我的工作目录更改为不存在的“目录”,因此会出现错误。R 添加了自己的“”,因此您的函数变为 setwd(""directory"")。您可以在 path.expand() 的帮助中阅读更多信息

于 2015-06-18T08:26:32.380 回答