I want to make the current file location as the working directory.
Using Rstudio (Works!):
# Author : Bhishan Poudel
# Program :
UPDATE: I realised that this answer didn't help at all, and I will post another one that does the trick.
Insofar the code you want to run doesn't need any additional arguments, a solution as sketched below, using eval(expr, envir) might do the trick.
Consider the following example using print(environment()), which should return environment: R_GlobalEnv when used on the command line. The function test_1 will print information about the internal environment that is created when the function is called, whereas the function test_2 will return the desired result.
test_1 <- function(){
print(environment())
}
test_2 <- function(){
.expr <- quote({
print(environment())
})
.envir <- sys.frame(which = -1)
eval(expr = .expr,
envir = .envir)
}
The sys.frame(which = -1) ensures that the expression is evaluated in the environment where the function is called. If you are certain that you always want to use the global environment, then it's better to use .GlobalEnv. It's also important to quote the expression you want to use, otherwise it might not work as desired.
A nice feature of this solution is that you don't need to tweak the code you want to put into the function, just quote it.
Finally: It's possible to extend this approach such that your function can take arguments that then will be given to the code you want to evaluate in another environment. This will however require a bit of non-trivial tweaking upon the expression you want to evaluate; you might need to use the bquote + .() construction - and you might in addition also need to use call and do.call.