Skip to content
Advertisement

How to use different versions of R kernels in VS code Jupyter notebooks when using Linux

I can’t find a way to use various versions of the R kernel in VS code and be able to change between them easily. Obviously uninstalling one kernel version (e.g 4.0.0) and installing another (3.6.0) one is not a practical option.

I already have installed:

Jupyter Extension for Visual Studio Code (essential)
R Extension for Visual Studio Code (optional)
library(IRkernel) (essential as highlighted here)
library(languageserver) (optional)

It works well for my default system R kernel (latest version). but how can I easily swap among other older versions I also have installed and have to use to run older projects with older library requirements ?

Top right of VS code one can change among different version of the python kernel, but only one kernel is shown up for R and it defaults to the system installation /usr/lib/R/bin/R

How can I add more?

Advertisement

Answer

You can add any number of custom kernels to the folder ~/.local/share/jupyter/kernels

If you already have one R kernel installed and working, there should be an ‘r’ folder already in this directory containing a kernel.json file with the following content:

{"argv": ["/usr/lib/R/bin/R", "--slave", "-e", "IRkernel::main()", "--args", "{connection_file}"],
 "display_name":"R",
 "language":"R"
}

This allows this kernel to be available through the top right kernel options in VS code and you can add more by adding new folders to this directory (one per new kernel) with a corresponding kernel.json file inside. See more about adding kernels here. For example creating a new ‘r3.6.3’ folder with a new kernel.json containing:

{"argv": [".renv/versions/3.6.3/bin/R", "--slave", "-e", "IRkernel::main()", "--args", "{connection_file}"],
 "display_name":"R 3.6.3",
 "language":"R"
}

will add this version of the kernel to the options available. Notice that you only need to specify the path location of the kernel version wherever you have it installed.

Also notice I’m using the library renv to manage various versions of R. If you don’t want to create various folders for different kernels each time, you can combine renv to handle multiple versions of R and make sure the file does not point to any particular version but simply invokes R,

{"argv": ["R", "--slave", "-e", "IRkernel::main()", "--args", "{connection_file}"],
 "display_name":"R renv",
 "language":"R"
}

which will trigger VS code to use whatever version of R you are using at that moment via renv. See here for more on the latter library

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement