使用 here() 函数上一级根目录

C. *_*ney 6 r

在开始向下目录级别之前,我想让 here 函数上升一个级别。

例如,我的项目在目录 '/parent/project_root/' 中,所以 here() 将其视为默认目录。我有一些我想在“parent/other_dir/”中读取的数据。我需要传递给 here() 什么参数才能让它首先上升到 'parent' 然后下降到 other_dir (相当于setwd('../'))?如果不需要,我宁愿不将 other_dir 移动到“project_root”中,但如果不可能,我可以做到。

Mak*_*212 6

library(here)
set_here(path='..')
Run Code Online (Sandbox Code Playgroud)

进入父目录

  • 是的,我会添加包调用,但我最初没有添加,因为 OP 问题专门针对 `here` 包 (3认同)
  • 似乎 `here()` 旨在始终指向项目的顶级目录,因此它并不是真正设计用于在更高级别上使用 `..` 的概念。如果你需要 `here('../')` 那么我猜 `here()` 应该设置为更高级别的目录,然后一切都与此相关。否则,您需要使用不同的方法来导航目录树。 (3认同)

Dev*_*ord 6

您可以简单地从路径中删除项目目录字符串:

gsub("project_root/", "", here(other_dir) )
Run Code Online (Sandbox Code Playgroud)

将“parent/project_root/other_dir/”转换为“parent/other_dir/”

或者,更优雅地使用stringr

here(other_dir) %>% str_remove("project_root/")
Run Code Online (Sandbox Code Playgroud)

这有点像黑客,但它适用于这样的用例:您想要here()指向项目根目录,但偶尔想要指向上面的项目目录中仍然普遍有效的路径。