在 R 中编写共享目录的相对路径
假设我和我的同事有一个共享目录,例如 SharePoint 驱动器。我们到任何给定目录的文件路径(例如 OurProject1)都将相同,唯一的区别是我们的用户名。
例如,我的路径将是: "C:/Users/JohnLennon/SharedDrive/SharedData/baseline_data"
而他们的路径将是: "C:/Users/RingoStarr/SharedDrive/SharedData/baseline_data “
我正在尝试编写一个函数,允许已映射共享驱动器的任何同事运行一个脚本来访问共享数据中的数据,而无需手动输入用户名。请记住,项目目录不是共享驱动器 - 如果我与同事共享此脚本,它将保留在共享目录之外,因此与项目相关的相对文件路径将不起作用。
我一直在尝试使用在函数中临时设置的绝对文件路径来解决此问题,该函数从 getwd() 推断目录路径的前半部分。所以该函数看起来有点像这样:
wd <- getwd() # get the users working dir
usr <- substr(wd, 1, 18) # extract the root down to the username
paste(usr, "SharedDrive/SharedData/baseline_data", sep = "") # prefix this onto the shared directory path
这对于 RingoStarr
来说效果很好,他的用户名中的字符数与 JohnLennon
相同,但是对于 GeorgeHarrison< /code>,还是所有其他用户?计算第二行的字符数显然是一种有限的方法。
我正在寻找对第二行的修改,该修改将从工作目录“盲目”导航,我们假设该工作目录是 "C:/Users/Username/"
的子目录到根以下两级目录(即在用户名目录中)。 ".."
在这里不起作用,因为我们不知道用户名目录 getwd()
中的位置。
如果存在的话,我也愿意采用不同的方法来解决问题
Let's say my colleagues and I have a shared directory, such as a SharePoint drive. Our file path to any given directory, say OurProject1 will be the same with the only difference being our username.
So for example my path will be: "C:/Users/JohnLennon/SharedDrive/SharedData/baseline_data"
While theirs will be: "C:/Users/RingoStarr/SharedDrive/SharedData/baseline_data"
I am trying to write a function that will allow any of my colleagues who has mapped the shared drive to run a script that accesses data in the shared data without them having to manually input their username. Keep in mind that the project directory is not the shared drive - that if I share this script with a colleague it will be kept outside of the shared directory and so relative file paths with regards to the project won't work.
I have been trying to approach this using an absolute file path set temporarily within the function that infers the first half of the directory path from getwd(). So the function looks a bit like this:
wd <- getwd() # get the users working dir
usr <- substr(wd, 1, 18) # extract the root down to the username
paste(usr, "SharedDrive/SharedData/baseline_data", sep = "") # prefix this onto the shared directory path
This works fine for RingoStarr
, who has the same number of characters in his username as JohnLennon
, but what about GeorgeHarrison
, or all the other users? Counting characters on line two is clearly a limited approach.
I am looking for a modification to line two that will navigate "blindly" from the working directory, which we assume to be a subdirectory of "C:/Users/Username/"
to two levels below the root directory (i.e. in the Username directory). ".."
won't work here as we don't know where abouts within the the Username directory getwd()
is.
I am also open to a different approach to the problem if one exists
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试
strsplit
,而不是substr
,然后使用coldapse
参数:Instead of
substr
, you can trystrsplit
and thenpaste
with thecollapse
argument: