在开始向下目录级别之前,我想让 here 函数上升一个级别。
例如,我的项目在目录 '/parent/project_root/' 中,所以 here() 将其视为默认目录。我有一些我想在“parent/other_dir/”中读取的数据。我需要传递给 here() 什么参数才能让它首先上升到 'parent' 然后下降到 other_dir (相当于setwd('../'))?如果不需要,我宁愿不将 other_dir 移动到“project_root”中,但如果不可能,我可以做到。
library(here)
set_here(path='..')
Run Code Online (Sandbox Code Playgroud)
进入父目录
您可以简单地从路径中删除项目目录字符串:
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()指向项目根目录,但偶尔想要指向上面的项目目录中仍然普遍有效的路径。