How can a source
d or Sweave
d file find out its own path?
Background:
I work a lot with .R scripts or .Rnw files. My projects are organized in a directory structure, but the path of the project's base directory frequently varies between different computers (e.g. because I just do parts of data analysis for someone else, and their directory structure is different from mine: I have projects base directories ~/Projects/StudentName/ or ~/Projects/Studentname/Projectname and most students who have just their one Project usually have it under ~/Measurements/ or ~/DataAnalysis/ or something the like - which wouldn't work for me).
So a line like
setwd (my.own.path ())
would be incredibly useful as it would allow to ensure the working directory is the base path of the project regardless of where that project actually is. Without the need that the user must think of setting the working directory.
Let me clarify: I look for a solution that works with pressing the editor's/IDE's source
or Sweave
Keyboard shortcut of the unthinking user.
In this article. Select Source File Path on the File menu to display, set, or append to the source path. This command is equivalent to pressing CTRL+P.
To extract filename from the file, we use “GetFileName()” method of “Path” class. This method is used to get the file name and extension of the specified path string. The returned value is null if the file path is null. Syntax: public static string GetFileName (string path);
Path. GetFileName(item. ToString)). This will give you only file name with extension from full file path.
To retrieve a file in Python, you need to know the exact path to reach the file, in Windows, you can view a particular file's path by right-clicking the File-> Properties-> General-> Location. Similarly, to run a script, the working directory needs to be set to the directory containing the script.
Just FYI, knitr
will setwd()
to the dir of the input file when (and only when) evaluating the code chunks, i.e. if you call knit('path/to/input.Rnw')
, the working dir will be temporarily switched to path/to/
. If you want to know the input dir in code chunks, currently you can call an unexported function knitr:::input_dir()
(I may export it in the future).
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