R

From Sinfronteras
Jump to: navigation, search

The R Project for Statistical Computing:

https://www.r-project.org/

https://www.r-project.org/

R is an open-source programming language that specializes in statistical computing and graphics. Supported by the R Foundation for Statistical Computing, it is widely used for developing statistical software and performing data analysis.



Installing R


Installing R on Ubuntu 18.04 using apt

https://www.digitalocean.com/community/tutorials/how-to-install-r-on-ubuntu-18-04

Because R is a fast-moving project, the latest stable version isn’t always available from Ubuntu’s repositories, so we’ll start by adding the external repository maintained by CRAN.

Let’s first add the relevant GPG key:

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

Once we have the trusted key, we can add the repository: (Note that if you’re not using 18.04, you can find the relevant repository from the R Project Ubuntu list, named for each release)

sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/'
sudo apt update

At this point, we're ready to install R with the following command:

sudo apt install r-base

This confirms that we've successfully installed R and entered its interactive shell:

R
sudo -i R



Where is R installed

R is in

/usr/lib/R 
or
/usr/lib64/R 

which is the default from doing apt-get install r-base.



Installing a specific R Version

Podemos ver las versiones disponibles de r-base con:

sudo apt policy r-base
r-base:
 Installed: 3.5.2-1bionic
 Candidate: 3.6.0-2bionic
 Version table:
    3.6.0-2bionic 500
       500 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ Packages
    3.6.0-1bionic 500
       500 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ Packages
    3.5.3-1bionic 500
       500 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ Packages
*** 3.5.2-1bionic 500
       500 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ Packages
       100 /var/lib/dpkg/status
    3.5.1-2bionic 500
       500 https://cloud.r-project.org/bin/linux/ubuntu bionic-cran35/ Packages
    3.5.1-1bionic 500


En general, si queremos installar una versión específica de un paquete:

sudo apt install r-base=3.5.1-2bionic

Sin embargo, en muchos casos no es tan fácil así. Cuando los paquetes tienen dependencias, la ejecución del comando anterior no resuelve las dependencias automáticamente. Si el paquete tiene muchas dependencia (como es el caso de r-base) la instalación se torna un poco complicada.

Al tratar de instalar «r-base» veremos que la única dependencia es el paquete «r-recommended». Entonces, antes de instalar la «r-base» tenemos que instalar «r-recommended=3.5.1-2bionic». Sin embargo, «r-recommended» tiene muchas dependencias; y aunque la ejecución de «sudo apt install r-recommended=3.5.1-2bionic» resulve las dependencias e instala el paquete, luego se presentan problemas. Lo que pasó cuando lo hice de esta forma fue que aparentemente se había instalado la versión deseada; pero cuando desplegaba la versión del R con «sudo R --version» o en el terminal del R «version» se mostraba la versión más reciente disponible en la Version table. Esto pasa porque al ejecutar «sudo apt install r-recommended=3.5.1-2bionic» se instala la versión deseada de «r-recommended=3.5.1-2bionic» pero con respecto a las dependencias, podría instalarse la versión más reciente disponible en la Version table.

Fui capaz de instalar una versión específica de la siguiente forma:

sudo apt-get install r-recommended=3.5.3-1bionic r-base-core=3.5.3-1bionic r-base-core-dbg=3.5.3-1bionic r-base-dev=3.5.3-1bionic r-cran-mgcv r-doc-html=3.5.3-1bionic r-cran-nlme=3.1.137-1cranBionic0
sudo apt-get install r-base=3.5.3-1bionic r-base-html=3.5.3-1bionic

Se debe notar que se debe ejecutar el comando apt-get con todas las dependencias en una sóla orden, sino se hace de esta manera, apt-get podría resolver dependencias e instalar versiones incorrectas de algunos paquetes.

Note que hemos especificado la versión «=3.5.3-1bionic» para todos los paquetes excepto para «r-cran-nlme=3.1.137-1cranBionic0». Las versiones de «r-cran-nlme» no siguen el mismo orden que «r-base» pero tuvimos también que indicar una versión específica de «r-cran-nlme» porque la versión más reciente de este paquete dependía de versiones más reciente de «r-base».


<br /

Compile and Install R from the source

Descargar R from: https://cran.r-project.org/src/base/R-3/

The above link debería estar disponible en la home-page de R Project: https://www.r-project.org/


Las instrucciones de como instalarlo se pueden encontrar en:


We need a FORTRAN compiler or perhaps f2c in addition to a C compiler to build R. Generalmente ya se encuentran instalados, sino:

sudo apt-get install gfortran
sudo apt-get install build-essential


Also, The readline package is required for compilation:

sudo apt-get install libreadline6 libreadline6-dev


The X11 headers are also needed:

sudo apt-get install xorg-dev


Java is also required (Java#Installing_the_Default_OpenJDK):

sudo apt install default-jdk


Luego:

./configure --prefix=$HOME/R   (directorio en donde queremos instalarlo)
make
make install

En los links the arriba, se encuentran algunos otros detalles con respecto a este paso: ./configure --prefix=$HOME/R


De esta forma, el ejecutable será:

/home/adelo/R/bin/R

y el directorio en donde serán instalados los paquetes será:

/home/adelo/R/lib/R/library

Por tanto, si queremos realizar una instalación manual de un paquete debemos considerar este path:

R CMD INSTALL -l  /home/adelo/R/lib/R/library  RTextTools_1.4.2.tar.gz



IDE for R


RStudio


Installing RStudio

https://linuxconfig.org/rstudio-on-ubuntu-18-04-bionic-beaver-linux

From the official RStudio download page, download the latest Ubuntu/Debian RStudio *.deb package available. At the time of writing the Ubuntu 18.04 Bionic package is not available yet. If this is still the case download the Ubuntu 16.04 Xenial package instead: https://www.rstudio.com/products/rstudio/download/#download

sudo gdebi rstudio-xenial-1.1.442-amd64.deb

To start RStudio:

rstudio



Jupyter


Installing packages


Installing packages from CRAN using the package manager

Part of R’s strength is its available abundance of add-on packages. For demonstration purposes, we'll install txtplot, a library that outputs ASCII graphs that include scatterplot, line plot, density plot, acf and bar charts. We'll start R as root so that the libraries will be available to all users automatically:

sudo -i R
> install.packages('txtplot')

When the installation is complete, we can load txtplot:

> library('txtplot')

If there are no error messages, the library has successfully loaded. Let’s put it in action now with an example which demonstrates a basic plotting function with axis labels. The example data, supplied by R's datasets package, contains the speed of cars and the distance required to stop based on data from the 1920s:

> txtplot(cars[,1], cars[,2], xlab = 'speed', ylab = 'distance')

      +----+-----------+------------+-----------+-----------+--+
  120 +                                                   *    +
      |                                                        |
d 100 +                                                   *    +
i     |                                    *                *  |
s  80 +                          *         *                   +
t     |                                       * *    *    *    |
a  60 +                          *  *      *    *      *       +
n     |                        *         * *  * *              |
c  40 +                *       * *    *  *    * *              +
e     |         *      *  * *  * *  *                          |
   20 +           *    *  * *       *                          +
      |  *      *    *                                         |
    0 +----+-----------+------------+-----------+-----------+--+
           5          10           15          20          25   
                                speed

If you are interested to learn more about txtplot, use help(txtplot) from within the R interpreter.



Package manager - Some important commmands

Display packages currently installed in your computer:

> installed.packages()

This produces a long output with each line containing a package, its version information, the packages it depends, and so on.


A more user-friendly, although less complete, list of the installed packages can be obtained by issuing:

> library()


The following command can be very useful as it allows you to check whether there are newer versions of your installed packages at CRAN:

> old.packages()


Moreover, you can use the following command to update all your installed packages:

> update.packages()



Package that provides functions to connect to MySQL databases

This package name is RMySQL. You just need to type the following command at R prompt:

> install.packages('RMySQL')



Installing package manually from a local file

https://cmdlinetips.com/2012/05/how-to-install-a-r-package-locally-and-load-it-easily/

A veces el package que queremos no se encuentra disponible para la versión de R que estamos usando. Esto pasa con package viejos. En estos casos es posible descargar la última versión del package e instalarlo a partir del archivo.

La última versión del package se puede descargar de la página https://cran.r-project.org

For example the package maxent is archived at: https://cran.r-project.org/src/contrib/Archive/maxent/

La instalación se realiza de la siguiente forma:

R CMD INSTALL -l  /usr/local/lib/R/site-library  RTextTools_1.4.2.tar.gz

Precisamente con el package RTextTools tuve este problema. El source de dicho package lo encontré aquí: https://cran.r-project.org/src/contrib/Archive/RTextTools/



Some important commands

To list all of the objects you've created:

ls()


To remove all of the objects you've created (clear the environment (workspace)):

remove(list = ls())

You can also remove individual objects:

remove(object)

You can also clear the environment on RStudio by just clicking the clear button (escova) under the Environment tab.


Para obtener la ayuda de un comando:

?commandName



Basic R tutorial