How to access to specify file in subfolder without change working directory In 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 :)


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')

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 :-)

Tags:

Csv

R