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.
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->.....
So i want to load data in abc.csv, def.csv and run code in pricing.R.
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")
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.
You can think of R as having a file explorer window open invisibly in the background. You can see the folder that's open at the moment by typing getwd() at the console. setwd() tells R to open a different folder instead. setwd('../') tells R to go up to a parent directory.
To list all files in a directory in R programming language we use list. files(). This function produces a list containing the names of files in the named directory. It returns a character vector containing the names of the files in the specified directories.
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')
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
Hope this helps.
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')
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.
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
And then, from R:
> setwd('/home/phuong') > data_abc <- read.csv('data_abc.csv') > data_def <- read.csv('data_def.csv') > source('pricing.R')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With