如何在R中不更改工作目录的情况下访问子文件夹中的指定文件?
在R中,我想访问子文件夹中的某些文件.但是我不想更改工作目录然后移回.它浪费了时间和时间.
In R, I want to access to some file in subfolder. But I don't want to change working directory then move back. It lost time and long.
例如,我在/home/phuong
文件夹上工作.
这是phuong的树结构.
For exmaple, I working on /home/phuong
folder.
Here is the tree structure of phuong.
phuong-> data1, data2, data3.
data1-> abc.csv, def.csv, script1.R
data2-> bond.csv, option.csv, pricing.R
data3->.....
所以我想在abc.csv,def.csv中加载数据并在price.R中运行代码.
So i want to load data in abc.csv, def.csv and run code in pricing.R.
因此,如果使用代码setwd
,它将使我浪费很多时间,并且看起来代码如此愚蠢,就像这样:
So if use code setwd
, it make me lost many time and look code so stupid, like this:
setwd("/home/phuong/data1" );
read.csv("abc.csv");
read.csv("def.csv");
setwd("/home/phuong/data2" );
source("pricing.R")
我浪费了很多时间从一个文件夹移动到另一个文件夹,但是所有这些都位于同一文件夹home/phuong/
中.
因此,我需要某种方法来访问子文件夹中的任何文件,而无需setwd
命令.
拜托,请帮助我.
I lost a lot of times to move from folder to another folder but all of them in the same folder home/phuong/
.
So I need some way to access to any file in subfolder without setwd
command.
Please help me , thks.
假设您的工作目录为/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')