Install the R kernel in DSW

更新时间:
复制 MD 格式

Data Science Workshop (DSW) runs on JupyterLab. To run R scripts and use R packages directly in JupyterLab, install the R kernel on your DSW instance.

Prerequisites

Before you begin, ensure that you have:

Install the R kernel

Step 1: Open the DSW instance

  1. Log on to the PAI console.

  2. In the left-side navigation pane, click Workspaces. On the Workspaces page, click the name of the workspace you want to manage.

  3. In the upper-left corner of the page, select your region.

  4. In the left-side navigation pane, choose Model Training > Data Science Workshop (DSW).

  5. Optional: On the Data Science Workshop (DSW) page, enter the name of a DSW instance or a keyword in the search box to search for the DSW instance.

  6. Find the instance you want to use, then click Open in the Actions column.

Step 2: Install R

In the JupyterLab terminal, run the following commands to install R from Ubuntu repositories using APT (Advanced Packaging Tool):

apt update
apt install r-base

If prompted with Proceed ([y]/n), enter y and press Enter.

Step 3: Install IRkernel

IRkernel is the R kernel package for Jupyter. Install it from within an R session.

  1. Start an R session:

    R
  2. Install the IRkernel package:

    install.packages('IRkernel')
  3. Register the kernel with Jupyter:

    IRkernel::installspec()
  4. Exit the R session:

    q()

Step 4: Verify the installation

Refresh the browser page that contains the Launcher tab, then open a new Launcher tab. If the R kernel is installed successfully, an R notebook option and an R console option are available.

image

Click R to create an R notebook and start using R in JupyterLab.

Example: Data analysis with R

The following example uses the built-in mtcars dataset to demonstrate basic data analysis in R: loading the dataset, calculating average horsepower (hp) by number of cylinders, and plotting the relationship between horsepower (hp) and miles per gallon (mpg).

Open a new R notebook and run the following code:

# Install the ggplot2 package.
install.packages("ggplot2")
library(ggplot2)

# Load the mtcars dataset.
data(mtcars)

# Print the first few rows.
head(mtcars)

# Calculate average horsepower (hp) by number of cylinders.
average_hp_by_cyl <- aggregate(mtcars$hp, by=list(mtcars$cyl), FUN=mean)
colnames(average_hp_by_cyl) <- c("cylinders", "average_hp")

# Print the result.
print(average_hp_by_cyl)

# Plot the relationship between horsepower (hp) and miles per gallon (mpg).
ggplot(mtcars, aes(x=mpg, y=hp)) +
  geom_point() +                          # Plot data points.
  geom_smooth(method="lm") +              # Add a linear regression line.
  labs(
    title="Horsepower versus Miles per Gallon",
    x="Miles per gallon (mpg)",
    y="Horsepower (hp)"
  )
image