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 /
You could use what Hadley calls a closure in Advanced R if I understand what you're after:
## Make a function that takes a path and another function
## and returns that same function with the path pre-progammed in
pathit <- function(FUN, path){
function(file, ...){
FUN(file=file.path(path, file), ...)
}
}
## generate new functions that have the path pre-programmed in
read.csv2b <- pathit(read.csv, "home/phuong/data1")
source2 <- pathit(source, "home/phuong/data2")
read.csv2b("abc.csv")
read.csv2b("def.csv")
source2("pricing.R")
If you have a lot of stuff to read in this may be worthwhile otherwise why not supply the whole path to the actual functions? If this isn't what you're after it was still a fun learning experience for me :-)
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')
For me, the most intuitive way to learn to navigate folders is by using list.files("../")
. You will see how upstream or downstream you need to navigate from your current location :)
I don't know if this is what you were looking for, but I have a library of files in a specific github folder that I source when I initialize a project in a new branch, and I found one solution online like this:
setwd("~/repos/library/all_the_things")
library_files <- list.files()
sapply(library_files, source)
which is great except now I'm starting every file in a directory where I wouldn't want to save plots etc., so I realized all it needed was this:
library_files <- list.files("~/repos/library/all_the_things", full.name=T)
sapply(library_files, source)
and now it runs them without changing directories.