How to use variables in renv::run() with Rscript

99 Views Asked by At

Follow up on this question:

From tsp answer: I believe a simpler way than the above answers: Rscript -e 'renv::run("/path/to/myscript.R")' It will pick up the renv environment from the base path. You can also specify the environment using the project parameter.

Is there any way to use a variable to define the /path/? if I have many scripts referencing the same path?

I tried to define a variable for the /path/, however since variables in bash does not work within single quote, I do not know how to make it work.

For example, say:

$SRC_DIR="/home/user/Rscript"

These will not work:

Rscript -e 'renv::run("$SRC_DIR""/to/myscript.R")'
Rscript -e 'renv::run("${SRC_DIR}""/to/myscript.R")'

Error: unexpected string constant in "renv::runn("${SRC_DIR}""/to/myscript.R""
1

There are 1 best solutions below

0
TimTeaFan On

I just tested, and this worked for me:

Rscript -e "renv::run(\"${SRC_DIR}/to/myscript.R\")"

We can escape the quotation marks within R \" (only the inner and not the outer quotation marks) and just build one string in which we inject SRC_DIR with the ${} sytnax.

To figure this out I played around with Rscript -e "print(...)" which helped a lot to see how R processes the input.