如何在Jupyter中从Python内核切换至R内核?解决R Markdown转ipynb后无法切换内核的问题
It sounds like your Jupyter setup either lacks a properly registered R kernel, or the converted notebook isn't configured to use it. Let's walk through the most effective fixes step by step:
1. Install and Register the R Kernel with Jupyter
Even if you have an R environment set up, Jupyter won't recognize it until you register the R kernel. Here's how to do that:
- Open your R console (or RStudio)
- Install the
IRkernelpackage, which connects R to Jupyter:install.packages("IRkernel") - Register the kernel so Jupyter can see it:
If you want this kernel available to all users on your system, addIRkernel::installspec()user = FALSE:IRkernel::installspec(user = FALSE)
Restart Jupyter after this, and you should see an "R" option in the kernel dropdown menu when you open your notebook.
2. Manually Set the Kernel in Your Existing Notebook
If the kernel still doesn't show up, or you want to force the notebook to use R by default, edit the notebook's metadata directly:
- Open
script.ipynbin a text editor (VS Code, nano, Sublime Text, etc.) - Look for the
"kernelspec"section near the top of the file—it probably looks like this:"kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" } - Replace it with the R kernel configuration (the
nameis usuallyir, but adjust if yours differs):"kernelspec": { "display_name": "R", "language": "r", "name": "ir" } - Save the file and reopen it in Jupyter—it should now load the R kernel automatically.
3. Alternative: Use rpy2 for Mixed Python/R Workflows
If you need to run R code within a Python notebook (instead of switching kernels entirely), fix the ModuleNotFoundError for rpy2:
- Install rpy2 in your Python environment using pip:
Note: You may need system dependencies first. For Ubuntu/Debian:pip install rpy2
For macOS (using Homebrew):sudo apt-get install r-base python3-dev libxml2-dev libcurl4-openssl-dev libssl-devbrew install r python - Once installed, load the rpy2 extension in your notebook:
%load_ext rpy2.ipython - Now you can use the
%%Rcell magic to run R code in dedicated cells:%%R # Example R code data <- c(10, 20, 30) print(mean(data))
4. Avoid the Issue Next Time: Convert with Kernel Specified
When using jupytext to convert your R Markdown file to ipynb, specify the R kernel upfront to skip manual configuration:
jupytext --to notebook --set-kernel ir script.Rmd
This will generate an ipynb file that uses the R kernel by default.
Content of the question comes from Stack Exchange, asked by Lerner Zhang

