【问题标题】:Automatically Set Working Directory to Currently Opened Folder in R自动将工作目录设置为 R 中当前打开的文件夹
【发布时间】:2019-10-17 16:28:07
【问题描述】:

是否可以在 R 中自动将工作目录设置为当前打开的文件夹?

示例:假设我当前在我的计算机上打开了文件夹 example_dir。

现在,我想运行一些 R 代码来将此文件夹设置为我的工作目录,而不知道打开文件夹的名称。 R 代码应如下所示:

currently_opened_folder <- xxxxxxx some function extracting the path for example_dir xxxxxxxx
setwd(currently_opened_folder)

【问题讨论】:

    标签: r automation working-directory setwd


    【解决方案1】:

    感谢this article,我刚刚发现了如何从资源管理器窗口获取位置 URL。

    首先,在 PowerShell 中执行命令以检索活动资源管理器窗口的路径。然后,使用 grep 从命令返回中提取路径。最后,您需要删除“file:///”前缀并对 URL 进行解码(替换“%20”等特殊字符)。

    # Get location URL of opened Explorer windows
    location_url <- grep(
      "file", 
      system('powershell -command "$a = New-Object -com "Shell.Application"; $b = $a.windows() | select-object LocationURL; $b"', intern = TRUE),
      value = TRUE
    )
    
    # Check if there are multiple windows opened
    if (length(location_url) > 1) {
      message("Multiple Explorer windows are opened.")
    } else {
      # Clean paths
      path <- gsub("file:///", "", URLdecode(location_url))
      setwd(path)
    }
    

    【讨论】:

    • 太棒了,正是我想要的。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2015-04-17
    • 2017-11-16
    • 2018-02-24
    • 1970-01-01
    • 2020-02-17
    • 2020-03-30
    • 2016-05-06
    • 1970-01-01
    相关资源
    最近更新 更多