rjupyter-notebookjupyterjupyter-labjupyter-irkernel

How to source R code from another Jupyter notebook file?


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


Solution

  • 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