Migrating R code from RStudio scripts to Jupyter notebooks

To migrate your code from RStudio scripts to Jupyter notebooks, first create a new Jupyter notebook that uses one of the supported R runtimes and then install any additional R Packages in its runtime. Finally, migrate your files from RStudio to your new Jupyter notebook and run your code.

Before you begin:

Before migration, review your R scripts to identify:

  • Dependencies: List all required packages
  • Data sources: File paths, database connections, APIs
  • Environment variables: Configuration settings
  • Custom functions: User-defined functions
  • Output formats: Plots, tables, files

To migrate your code from RStudio scripts to Jupyter notebooks:

  1. Launch RStudio IDE and export your R code, custom functions, and any required data files to your local machine. See Downloading a file from RStudio

  2. Open your watsonx.ai Studio project and then create a new Jupyter notebook that uses one of the supported R runtimes. See Creating and managing notebooks and Default CPU runtime templates.

  3. Install any additional, required R Packages in the notebook's runtime.

    Example:

    # Core data manipulation packages
    install.packages(c(
    "tidyverse",    # Data manipulation and visualization
    "dplyr",        # Data manipulation
    "readr",        # Reading data
    "tidyr",        # Data tidying
    "lubridate"     # Date/time handling
    ))
    
    # Visualization packages
    install.packages(c(
    "plotly",       # Interactive plots
    "ggplot2",      # Plotting
    "ggraph",       # Network graphs
    "DT",           # Interactive tables
    "htmlwidgets"   # HTML widgets
    ))
    
    
    # Spark integration (if needed)
    install.packages(c(
    "sparklyr",     # Spark interface
    "arrow"         # Apache Arrow
    ))
    
    # Python integration
    install.packages(c(
    "reticulate",   # Python integration
    "keras",        # Deep learning
    "tensorflow"    # TensorFlow
    ))
    
  4. Add data assets that you exported from RStudio to your project. See Adding data to your project.

  5. Load data assets from your project to your notebook. See Loading data through code snippets.

  6. Add the R code that you exported from RStudio to the cells in your Jupyter notebook and then execute the notebook.

Code Conversion Examples

Example 1: Basic Data Analysis

The following example demonstrates how to load a sales data file into a Jupyter notebook, analyze it to generate a monthly sales summary, and visualize the results in a graph.

Cell 1: load R libaries

library(dplyr)
library(ggplot2)

Cell 2: load data

Use the Insert to code tool to generate a code snippet for loading data into your notebook.

Cell 3: compute monthly summary statistics from a dataset

monthly_sales <- sales %>%
  group_by(month) %>%
  summarise(
    total_sales = sum(amount),
    avg_sales = mean(amount),
    count = n()
  ) %>%
  arrange(month)
print(monthly_sales)

Cell 4: visualize data

# Visualization
options(repr.plot.width = 12, repr.plot.height = 6)
ggplot(monthly_sales, aes(x = month, y = total_sales)) +
  geom_bar(stat = "identity", fill = "steelblue") +
  geom_text(aes(label = scales::comma(total_sales)),
            vjust = -0.5, size = 3) +
  theme_minimal() +
  labs(title = "Monthly Sales Performance",
       x = "Month",
       y = "Total Sales ($)") +
  scale_y_continuous(labels = scales::comma)

Example 2: Save data as a project asset by using the ibm-watson-studio-lib library

For reference, see ibm-watson-studio-lib for R.

Cell 1: Add a project access token for ibm-watson-studio-lib

For details, see Manually adding the project access token.

Cell 2: Inspect the current project and its assets

wslib$here$get_name()
wslib$show(wslib$list_stored_data())

Cell 3: Save a CSV file as a project asset

wslib$save_data("testasset.csv", charToRaw("1,2,3"), overwrite=TRUE)
wslib$show(wslib$list_stored_data())

Cell 4: Fetch the data from the CSV file

my_file <- wslib$load_data("testasset.csv")

Cell 5: Read the CSV data file into a data frame

df <-  read.csv(text = rawToChar(my_file))
head(df)