r - 自动将工作目录设置为 R 中当前打开的文件夹

标签 r automation working-directory setwd

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

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

enter image description here

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

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

最佳答案

感谢 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)
}

关于r - 自动将工作目录设置为 R 中当前打开的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58437077/

相关文章:

r - 确定 R 中向量的最小值

r - 如何解决 pandoc 问题

javascript - 在 CasperJS 中等待网页警报

c# - 将进程的工作目录设置为 exe 的路径?

dll - 从 lisp 脚本、工作目录和路径加载库

makefile - makefile 的当前工作目录

跨嵌套列表的 rbind 数据帧

r - 过滤每组中间行

java - 每 x 分钟调用一个方法

internet-explorer - 控制 IE 的程序能否检测到是否遇到 HTTP 30x 代码?