How to source R code from another Jupyter notebook file?

1.6k views Asked by At

I am new to using the Jupyter notebook with R kernel.

I have R code written in two files Settings.ipynb and Main_data.ipynb.

My Settings.ipynb file has a lot of details. I am showing sample details below

Schema = "dist"
resultsSchema = "results"
sourceName = "hos"
dbms = "postgresql" #Should be "sql server", "oracle", "postgresql" or "redshift"

user <- "hos"
pw <- "hos"
server <- "localhost/hos"
port <- "9763"

I would like to source Settings file in Main_data code file.

When I was using R studio, it was easy as I just use the below

 source('Settings.R')

But now in Main_data Jupyter Notebook with R kernel, when I write the below piece of code

 source('Settings.R')  # settings file is in same directory as main_data file

I get the below error

Error in source("Settings.R"): Settings.R:2:11: unexpected '['
1: {
2:  "cells": [
             ^
Traceback:

1. source("Settings.R")

When I try the below, I get another error as shown below

source('Settings.ipynb')

Error in source("Settings.ipynb"): Settings.ipynb:2:11: unexpected '['
1: {
2:  "cells": [
             ^
Traceback:

1. source("Settings.ipynb")

How can I source an R code and what is the right way to save it (.ipynb or .R format in a jupyter notebook (which uses R kernel)). Can you help me with this please?

updated screenshot

strong text

2

There are 2 answers

5
akrun On BEST ANSWER

We could create a .INI file in the same working directory (or different) and use ConfigParser to parse all the elements. The .INI file would be

Settings.INI

[settings-info]
schema = dist
resultsSchema = results
sourceName = hos
dbms = postgresql

user = hos
pw = hos
server = localhost/hos

Then, we initialize a parser object, read the contents from the file. We could have multiple subheadings (here it is only 'settings-info') and extract the components using either [[ or $

library(ConfigParser)
props <- ConfigParser$new()
props <- props$read("Settings.INI")$data
props[["settings-info"]]$schema

From the Jupyter notebook

enter image description here

the 'Settings.INI' file

enter image description here

0
The Great On

Trying to save a Jupyter notebook file in .R format will not work as the format is a bit messed up (due to the presence of things like { "cells" : [....". You can verify this by opening your .R file in Jupyter Notebook.

However, you can use a vim editor/R studio to create a .R file. This will allow you to have the contents as is without any format issues such as { "cells" : [....".

Later from another jupyter notebook, you can import/source the .R file created using vim editor/R studio. This resolved the issue for me.

In summary, don't use jupyter notebook to create .R file and source them using another jupyter notebook file.