且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在R中不更改工作目录的情况下访问子文件夹中的指定文件?

更新时间:2023-09-20 12:32:16

假设您的工作目录为/home/hermie,并且您要从当前WD下方的目录(假设为/home/hermie/data)加载.csv文件,您可以简单地做到这一点:

Assuming your working directory is /home/hermie and you want to load a .csv file from a directory below your current WD (let's say /home/hermie/data), you can simply do this:

setwd('/home/hermie')
myData <- read.csv('./data/myCsvFile.csv')

当然,您也可以在目录树中向上"导航.假设您要在Bob的主目录(/home/bob)中加载文件.您可以按照以下步骤进行操作:

Of course you could also navigate "upwards" in the directory tree. Let's say you want to load a file in Bob's home directory (/home/bob). You can do it as follows:

setwd('/home/hermie')
data_from_bob <- read.csv('../bob/otherDataFile.csv') # Of course, this will work
                                                      # only if you can read
                                                      # files from that directory

希望这会有所帮助.

更新

Update

我认为您希望有人为您编写解决方案...,我建议这样做:

Somehow I think you want someone to write the solution for you... and I propose this:

> setwd('/home/phuong')
> data_abc <- read.csv('./data1/abc.csv')
> data_def <- read.csv('./data1/def.csv')
> source('./data2/pricing.R')

写这个真的难吗?如果您在此过程中的每一步都更改了WD,则您将不得不编写更多内容.

Is it really so dificult to write this? You would have to write much more if you changed your WD on every step of the way.

关于我对符号链接的建议,在您的bash终端上,您可以执行以下操作:

And, about my sugestion on symlinks, on your bash terminal you could do something like this:

$ cd /home/phuong
$ ln -s ./data1/abc.csv data1_abc.csv
$ ln -s ./data1/def.csv data1_def.csv
$ ln -s ./data2/pricing.R pricing.R

然后,从R:

> setwd('/home/phuong')
> data_abc <- read.csv('data_abc.csv')
> data_def <- read.csv('data_def.csv')
> source('pricing.R')