【问题标题】:Setting working directory through a function通过函数设置工作目录
【发布时间】:2016-03-29 16:11:12
【问题描述】:

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

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

   }

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

提前感谢您的帮助。

【问题讨论】:

  • 尝试使用setwd(paste0(getwd(), "/directory")paste 插入一个空格。

标签: r function setwd


【解决方案1】:

试试这个:

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

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

myfunction <- function(directory) setwd(directory)

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

myfunction <- setwd

【讨论】:

    【解决方案2】:

    我不知道,但如果您有兴趣,这也可能会有所帮助:

    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)
    

    【讨论】:

      【解决方案3】:

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

      我的函数 setwd(目录)
      }

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-27
        • 1970-01-01
        • 1970-01-01
        • 2015-01-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多