Install the R kernel in DSW
DSW instances integrate open-source JupyterLab. After you install the R kernel, you can run R scripts in notebooks for data analytics.
Prerequisites
A DSW instance is created. For more information, see Create a DSW instance.
Install the R kernel
On the DSW instance page, open the terminal and perform the following operations.
Install R
Run the following commands to install R by using the Ubuntu package management tool APT.
When
Proceed ([y]/n)is displayed during the execution, enteryand press Enter.apt update apt install r-baseInstall IRkernel
Install IRkernel, the Jupyter kernel for R. In the terminal, enter
Rand press Enter to start the R environment. Then run the following commands:install.packages('IRkernel') IRkernel::installspec()After the installation is complete, exit the R environment.
q()Return to the Launcher page and refresh the page to verify that the R environment is installed.
Open a new Launcher page in the notebook area. The R kernel option is displayed. Select R to create a notebook and start using R in JupyterLab.
Example: Data analysis with R
Run the following commands in sequence to create an R kernel notebook. Use the built-in mtcars dataset to calculate the average horsepower (hp) for each car type, and use the ggplot2 package to plot the relationship between horsepower and miles per gallon (mpg).
install.packages("ggplot2")Run the following code in the notebook:
# Load the required package.
library(ggplot2)
# Use the built-in mtcars dataset.
data(mtcars)
# Print the first few rows.
head(mtcars)
# Calculate the average horsepower 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 average horsepower.
print(average_hp_by_cyl)
# Plot the relationship between horsepower and miles per gallon.
ggplot(mtcars, aes(x=mpg, y=hp)) +
geom_point() +
geom_smooth(method="lm") +
labs(title="horsepower versus miles per gallon", x="miles per gallon (mpg)", y="horsepower (hp)") mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
cylinders average_hp
1 4 82.63636
2 6 122.28571
3 8 209.21429
`geom_smooth()` using formula = 'y ~ x'