如何在Ubuntu 18.04上安装R

时间:2020-03-05 15:31:31  来源:igfitidea点击:

R是一种快速增长的开源编程语言和免费环境,专门从事统计计算和图形表示。
它受到R统计计算基金会的支持,主要由统计学家和数据挖掘人员用于开发统计软件和执行数据分析。

本教程将指导我们完成在Ubuntu 18.04计算机上安装R的步骤。

准备工作

在开始本教程之前,我们需要一台具有以下功能的Ubuntu 18.04计算机:

  • 至少1G的内存。如果系统的内存不足1GB,则可以创建交换文件。
  • 具有sudo特权的非root用户。

在Ubuntu上安装R

在撰写本文时,R的最新稳定版本是3.5版。
Ubuntu存储库中的R软件包通常已过时,因此我们将通过添加CRAN维护的存储库来安装R。

要在Ubuntu 18.04上安装R的最新稳定版本,请按照以下步骤操作:

  • 安装通过HTTPS添加新存储库所需的软件包:
sudo apt install apt-transport-https software-properties-common
  • 使用以下命令启用CRAN存储库并将CRAN GPG密钥添加到系统:
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/'
  • 现在已经添加了apt仓库,更新软件包列表并通过输入以下命令安装R软件包:
sudo apt updatesudo apt install r-base
  • 要验证安装是否成功,请运行以下命令,该命令将打印R版本:
R --version
R version 3.5.1 (2016-07-02) -- "Feather Spray"
Copyright (C) 2016 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under the terms of the
GNU General Public License versions 2 or 3.
For more information about these matters see
http://www.gnu.org/licenses/.

从CRAN安装R软件包

R之所以如此受欢迎的主要原因之一是可以通过综合R存档网络(CRAN)获得大量的软件包。

安装“ build-essential”软件包,其中包含编译R软件包所需的工具。

sudo apt install build-essential

为了演示起见,我们将安装名为'stringr'的软件包,该软件包可快速,正确地实现常见的字符串操作。

当以root身份启动时,软件包将在全局安装,并可供所有系统用户使用。
如果我们在不使用sudo的情况下启动R,则会为用户建立一个个人库。

首先以根用户身份打开R控制台:

sudo -i R
R version 3.5.1 (2016-07-02) -- "Feather Spray"
Copyright (C) 2016 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
  Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
>

以下所有命令均在R控制台中执行。

通过键入以下命令安装“ stringr”软件包:

install.packages("stringr")

安装将花费一些时间,一旦完成,请使用以下命令加载库:

library(stringr)

创建一个名为'tutorial'的简单字符向量:

tutorial <- c("How", "to", "Install", "R", "on", "Ubuntu", "18.04")

运行以下函数,该函数将打印字符串的长度:

str_length(tutorial)
[1] 3 2 7 1 2 6 5

我们可以在“按名称提供的CRAN软件包”中找到更多R软件包,并使用'install.packages()'安装它们。