简体   繁体   中英

how can i get the current file directory in R

I have seen many related answers here,but i didn't get a proper way to solve my problem under windows system... I know the link the similar question I got that setwd() can locate the directory what i want,however,my R script may move to another directory without any modification,so I want to know the current file directory,becase there are expression like source(...) ,this called source file and the execution file under the same parent directory in a R project,how I can do? any help appreciated.

You can get your current directory using the getwd() function and give it a name, say:

cpath = getwd()

Another useful function is the file.path , which can help you specify new directories with simple syntax. For example, you want to get the directory that is one level "above" the current directory, you can use:

upp.dir = file.path("..", "cpath")

This gives upp.dir as "../Your_Current_Dir" . How about changing to another folder (called Folder_A) in current directory? Use:

folderA = file.path("cpath", "Folder_A")

These may help easy navigate the file system.

Basically, if you write scripts and those scripts depend on where they are, then you are Doing It Wrong.

Write code in packages. Parameterise functions to make them generally applicable. If you have folders with data in, then make one of those parameters a folder.

A script called with source() cannot reliably locate itself, but that shouldn't be a problem, because WHATEVER CALLED THE SCRIPT knows where the script is (it has to, or how else can it call it?) so it could pass that as a parameter. Something like:

 > youarehere = "C:\foo\"
 > source("C:\foo\bar.R")

and now bar.R can do setwd(youarehere) and it will work, even if it is badly written such that it relies on sourcing other code in its containing folder.

Or you can do:

> setwd(youarehere)
> source("bar.R")

in your calling function.

But really, its a fail, its a sign of badly written code. Use functions, write packages, use devtools, its really not that hard, then your code will work anywhere and you wont be writing stupid scripts that are a twisty turny maze of source() calls.

Stay classy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM