我是 R 新手。我在通过函数设置工作目录时遇到了麻烦。这是我尝试过的:
myfunction<-function(directory)
{
setwd(paste(getwd(),("/directory"))
}
当我运行 myfunction("name") 时出现错误:无法更改工作目录。
提前感谢您的帮助。
尝试这个:
myfunction <- function(directory) setwd( file.path(getwd(), directory) )
或意识到这getwd()
是默认设置,因此无需指定:
myfunction <- function(directory) setwd(directory)
或意识到您的函数实际上执行与setwd
此相同的功能:
myfunction <- setwd
我不知道,但是如果您有兴趣,这也可能会有所帮助:
https://github.com/imanojkumar/MyFunctions1/blob/master/README.md
source("https://raw.githubusercontent.com/imanojkumar/MyFunctions1/master/ChangeDirectory.R")
上面的源文件包含以下三个代码:
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)
}
myfunction(directory)
您面临的问题是使用“/目录”。如果您只使用目录而不是“目录” ,您将获得结果,如下所示:
我的函数 <- 函数(目录){
setwd(目录)
}
如果您使用粘贴功能,输出将是一个字符串,最后它会被解释为将我的工作目录更改为不存在的“目录”,因此会出现错误。R 添加了自己的“”,因此您的函数变为 setwd(""directory"")。您可以在 path.expand() 的帮助中阅读更多信息