如何在 Ubuntu 上安装和使用 R 语言
R语言

> 
> 这个教程指导你如何在 Ubuntu 上安装 R 语言。你也将同时学习到如何在 Ubuntu 上用不同方法运行简单的 R 语言程序。
> 
> 
> 


[R](https://www.r-project.org/)，和 Python 一样，它是在统计计算和图形处理上最常用的编程语言，易于处理数据。随着数据分析、数据可视化、数据科学（机器学习热）的火热化，对于想深入这一领域的人来说，它是一个很好的工具。


R 语言的优点是它的语法非常简练，你可以找到它的很多实际使用的教程或指南。


本文将介绍包含如何在 Ubuntu 下安装 R 语言，也会介绍在 Linux 下如何运行第一个 R 程序。


![](/data/attachment/album/201909/11/115259umnrin57vlrrhixl.jpg)


### 如何在 Ubuntu 上安装 R 语言


R 默认在 Ubuntu 的软件库里。用以下命令很容易安装：



```
sudo apt install r-base
```

请注意这可能会安装一个较老的版本。在我写这篇文字的时候，Ubuntu 提供的是 3.4，但是最新的是3.6。


*我建议除非你必须使用最新版本，否则直接使用 Ubuntu 的配套版本。*


#### 如何在 Ubuntu 上安装最新 3.6 版本的 R 环境


如果想安装最新的版本（或特殊情况指定版本），你必须用 [CRAN](https://cran.r-project.org/)（Comprehensive R Archive Network）。这个是 R 最新版本的镜像列表。


如需获取 3.6 的版本，需要添加镜像到你的源索引里。我已经简化其命令如下：



```
sudo add-apt-repository "deb https://cloud.r-project.org/bin/linux/ubuntu $(lsb_release -cs)-cran35/"
```

下面你需要添加密钥到服务器中：



```
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9
```

然后更新服务器信息并安装R环境：



```
sudo apt update
sudo apt install r-base
```

就这样安装完成。


### 如何在 Ubuntu 下使用 R 语言编程


R 的用法多样，我将介绍运行多个运行 R 语言的方式。


#### R 语言的交互模式


安装了 R 语言后，你可以在控制台上直接运行：



```
R
```

这样会打开交互模式：


![R Interactive Mode](/data/attachment/album/201909/11/115303c9i5c3zxw5luwfi3.png)


R 语言的控制台与 Python 和 Haskell 的交互模式很类似。你可以输入 R 命令做一些基本的数学运算，例如：



```
> 20+40
[1] 60

> print ("Hello World!")
[1] "Hello World!"
```

你可以测试绘图：


![R Plotting](/data/attachment/album/201909/11/115307gb4wjy3jgmjyokbj.jpg)


如果想退出可以用 `q()`或按下 `CTRL+c`键。接着你会被提示是否保存工作空间镜像；工作空间是创建变量的环境。


#### 用 R 脚本运行程序


第二种运行 R 程序的方式是直接在 Linux 命令行下运行。你可以用 `RScript` 执行，它是一个包含 `r-base` 软件包的工具。


首先，你需要用你在 [Linux 下常用的编辑器](https://itsfoss.com/best-modern-open-source-code-editors-for-linux/)保存 R 程序到文件。文件的扩展名必须是 `.r`。


下面是一个打印 “Hello World” 的 R 程序。你可以保存其为 `hello.r`。



```
print("Hello World!")
a <- rnorm(100)
plot(a)
```

用下面命令运行 R 程序：



```
Rscript hello.r
```

你会得到如下输出结果：



```
[1] "Hello World!"
```

结果将会保存到当前工作目录，文件名为 `Rplots.pdf`：


![Rplots.pdf](/data/attachment/album/201909/11/115309u0ra26orxl9p5o0t.png)


小提示：`Rscript` 默认不会加载 `methods` 包。确保在脚本中[显式加载](https://www.dummies.com/programming/r/how-to-install-load-and-unload-packages-in-r/)它。


#### 在 Ubuntu 下用 RStudio 运行 R 语言


最常见的 R 环境是 [RStudio](https://www.rstudio.com/)，这是一个强大的跨平台的开源 IDE。你可以用 deb 文件在 Ubuntu 上安装它。下载 deb 文件的链接如下。你需要向下滚动找到 Ubuntu 下的 DEB 文件。


* [下载 Ubuntu 的 Rstudio](https://www.rstudio.com/products/rstudio/download/#download)


下载了 DEB 文件后，直接点击安装。


下载后从菜单搜索启动它。程序主界面会弹出如下：


![RStudio 主界面](/data/attachment/album/201909/11/115311e66zyyfzdfyfczfa.jpg)


现在可以看到和 R 命令终端一样的工作台。


创建一个文件：点击顶栏 “File” 然后选择 “New File > Rscript”（或 `CTRL+Shift+n`）：


![RStudio 新建文件](/data/attachment/album/201909/11/115313co2zwcja9166w91c.png)


按下 `CTRL+s` 保存文件选择路径和命名：


![RStudio 保存文件](/data/attachment/album/201909/11/115314zak1eqmqa664uzhk.png)


这样做了后，点击 “Session > Set Working Directory > To Source File Location” 修改工作目录为你的脚本路径：


![RStudio 工作目录](/data/attachment/album/201909/11/115315yj9f9zzblss499f4.png)


现在一切准备就绪！编写代码然后点击运行。你可以在控制台和图形窗口看到结果：


![RStudio 运行](/data/attachment/album/201909/11/115316h7m55ecn6qp6cwwg.jpg)


### 结束语


这篇文章中展示了如何在 Ubuntu 下使用 R 语言。包含了以下几个方面：R 控制台 —— 可用于测试，Rscript —— 终端达人操作，RStudio —— 你想要的 IDE。


无论你正在从事数据科学或只是热爱数据统计，作为一个数据分析的完美工具，R 都是一个比较好的编程装备。


你想使用 R 吗？你入门了吗？让我们了解你是如何学习 R 的以及为什么要学习 R!




---


via: <https://itsfoss.com/install-r-ubuntu/>


作者：[Sergiu](https://itsfoss.com/author/sergiu/) 选题：[lujun9972](https://github.com/lujun9972) 译者：[guevaraya](https://github.com/guevaraya) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
*Brief: This tutorial teaches you to install R on Ubuntu. You’ll also learn how to run your first R program in Ubuntu using various methods.*

[R](https://www.r-project.org/), together with Python, is the most commonly used programming language for statistical computing and graphics, making it easy to work with data. With the growing interest in data analysis, data visualization, data science (the machine learning craze), it is now more popular than ever and is a great tool for anyone looking to dive into this fields.

The good thing about R is that its syntax is pretty straight-forward and you can find many tutorials/guides on how R is used in the real world.

In this article, I’ll cover how to install R on Ubuntu Linux. I’ll also show you how to run your first R program in Linux.

![Install R On Ubuntu](https://itsfoss.com/content/images/wordpress/2019/06/install-r-on-ubuntu-800x450.jpg)

## Installing R on Ubuntu

**R** is included in the Ubuntu repositories. It can be easily installed using:

`sudo apt install r-base`


Do note that this may install a slightly older version. At the time of writing this article, Ubuntu offers version 3.4 whereas the latest is version 3.6.

*I advise sticking with whichever version Ubuntu provides unless you must use the newer version.*

In order to get the latest version (or any specific version for that matter), you must use ** CRAN** (The Comprehensive R Archive Network). This is a list of mirrors for downloading the latest version of R. Click on the next section to learn how to install the latest version of R on Ubuntu.

**How to install latest R version 3.6 on Ubuntu (click to expand)**

To get the R version 3.6, you need to add the mirror to your sources list. I have simplified it for you in this command:

sudo add-apt-repository "deb https://cloud.r-project.org/bin/linux/ubuntu $(lsb_release -cs)-cran35/"

Now you should add the key for the repository:

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9

And then update the repository information and install R:

sudo apt update sudo apt install r-base

That’s it.

## Using R programming on Ubuntu

R has more than one use. I’ll go over several methods you can use to run R programs.

### Interactive Mode in R

After having installed **R**, you can run the console using:

`R`


This should open up the interactive mode:

![R Interactive Mode](https://itsfoss.com/content/images/wordpress/2019/06/r_interactive_mode.png?fit=800%2C516&ssl=1)

This R console is very similar to the **Python** and **Haskell** interactive prompts. You can enter any **R** command and you can do basic mathematical computations. For example:

```
> 20+40
[1] 60
> print ("Hello World!")
[1] "Hello World!"
```


You could test plotting too:

![R Plotting](https://itsfoss.com/content/images/wordpress/2019/06/r_plotting.jpg?fit=800%2C434&ssl=1)

You can **quit** using **q()** or pressing **CTRL+c**. When doing so, you will be asked if you want to save a workspace** **image; a workspace** **is an environment for created variables.

### Running R program with Rscript

The second way to run R programs is in directly on the Linux command line. You can do so using **RScript**, a utility included with **r-base**.

First, you have to save your R program to a file using your [favorite code editor on Linux](https://itsfoss.com/best-modern-open-source-code-editors-for-linux/). The file extension should be .r.

This is my sample R program printing “Hello World”. I have saved it in a file name hello.r.

```
print("Hello World!")
a <- rnorm(100)
plot(a)
```


To run the R program, use the command like this:

`Rscript hello.r`


You should get back the output:

`[1] "Hello World!"`


The plot is going to be saved in the working directory, to a file named **Rplots.pdf**:

![Rplots.pdf](https://itsfoss.com/content/images/wordpress/2019/06/rplots_pdf.png?fit=800%2C539&ssl=1)

**Note:** *Rscript **doesn’t load the **methods **package by default. Make sure to load it explicitly in your script*.

### Run R scripts with RStudio in Ubuntu

The most common way to use **R** is using [RStudio](https://www.rstudio.com/), a great cross-platform open source IDE. You can [install it using deb file in Ubuntu](https://itsfoss.com/install-deb-files-ubuntu/). Download the deb file from the link below. You’ll have to scroll down a bit to locate the DEB files for Ubuntu.

Once you download the DEB file, just double click on it to install it.

Once installed, search for it in the menu and start it. The home window of the application should pop up:

![RStudio Home](https://itsfoss.com/content/images/wordpress/2019/06/rstudio_home.jpg?fit=800%2C603&ssl=1)

Here you have a working console, just like the one you got in the terminal with the **R** command.

To create a file, in the top bar click on **File** and select **New File > Rscript** (or **CTRL+Shift+n)**:

![RStudio New File](https://itsfoss.com/content/images/wordpress/2019/06/rstudio_new_file.png?fit=800%2C392&ssl=1)

Press **CTRL+s** to save the file and choose a location and a name it:

![RStudio Save File](https://itsfoss.com/content/images/wordpress/2019/06/rstudio_save_file.png?fit=800%2C258&ssl=1)

After doing so, click on **Session > Set Working Directory > To Source File Location** to change the working directory to the location of your script:

![RStudio Working Directory](https://itsfoss.com/content/images/wordpress/2019/06/rstudio_working_directory.png?fit=800%2C394&ssl=1)

You are now ready to go! Write in your code and click run. You should be able to see output both in the console and in the plotting window:

![RStudio Run](https://itsfoss.com/content/images/wordpress/2019/06/rstudio_run.jpg?fit=800%2C626&ssl=1)

**Wrapping Up**

In this article, I showed you step by step how to get started using the **R** programming language on an Ubuntu system. I covered several ways you can go about this: **R console** – useful for testing, **Rscript** – for the terminal lover, **RStudio** – the IDE for your needs.

Whether you are willing to get into data science or simply love statistics, **R** is a good addition to your programming arsenal, being the perfect tool for analyzing data.

If you are absolutely new to R, let me recommend you this excellent book that will teach you fundamentals of R. It’s available on Amazon Kindle.

[lasso box=”B00GC2LKOK” link_id=”14655″ ref=”learn-r-in-a-day” id=”101763″]

Do you use **R**? Are you just getting into it? Let us know more about how and why you use or want to learn to use **R**!