Install R

From 太極
Revision as of 13:46, 1 November 2023 by Brb (talk | contribs) (→‎Mac)
Jump to navigation Jump to search

rig

rig - The R Installation Manager by r-lib. Install, remove, configure R versions. Note rig automatically installed the "pak" R package when we call "rig add" unless we add ""--without-pak" option.

Mac

  • Setting up macOS as an R data science rig in 2023
    brew tap r-lib/rig  # add a new formula repository (github repository)
    brew tap            # list all repositories
    brew install --cask rig  # require PIV card & pin OR password for several times
                        # it can also be used to upgrade an existing version
    which brew          # /usr/local/bin/rig
    
    rig --version       # 0.6.0
    brew upgrade --cask rig  # upgrade rig 
                             # But it requires several entering of my password.
                             # Maybe it's easier to use the installer
    rig add --help
    rig add release # require PIV card & pin
                    # It installed R 4.2.2 but my R 4.2.1 is gone.                 
    rig list        # x86 CPU
    # * name  version    aliases
    # ------------------------------------------
    #   3.6   (R 3.6.0)
    #   4.0   (R 4.0.4)
    # * 4.2   (R 4.2.2)  release
    
    rig default 4.0  # switch from 4.2.2 to 4.0.4
    

    On my current M1 computer (ARM cpu)

    $ rig add release  # install the latest version
                 # It installed R 4.3.0 but R 4.2.2 is still available (& default)
    $ /Library/Frameworks/R.framework/Versions/4.3-arm64/Resources/bin/R 
                 # I don't need to "rig default" to get to another version of R
    $ rig list
    * name       version    aliases
    ------------------------------------------
    * 4.2-arm64  (R 4.2.2)
      4.3-arm64  (R 4.3.0)  release
    
    $ rig default 4.3-arm64
    $ rig default 4.2-arm64
    
  • What happens to my project containing renv environment that used a newer R after I switch to an older R?
    # Bootstrapping renv 0.16.0 --------------------------------------------------
    * Downloading renv 0.16.0 ... OK (downloaded source)
    * Installing renv 0.16.0 ... Done!
    * Successfully installed and loaded renv 0.16.0.
    ℹ Using R 4.0.4 (lockfile was generated with R 4.2.1)
    * Project '~/GBM' loaded. [renv 0.16.0]
    * The project library is out of sync with the lockfile.
    * Use `renv::restore()` to install packages recorded in the lockfile.
    
  • So how to use two versions of R at the same time? (x86 CPU)
    rig default 4.3-arm64 # this will affect the whole OS
                    # but it is OK to run "rig default 4.2-arm64" on another terminal
                    # and launch an instance of (a different version of) R
    rig rstudio 4.3-arm64 # for this specific process
    
  • How to launch a specific version of R from a specific directory? The document seems outdated. Note the "-n" parameter stands for "new" and is used to open a new instance of the application. Search for The macOS open Command.
    open -n -a RStudio ~/proj/proj.Rproj \
      --env RSTUDIO_WHICH_R=/Library/Frameworks/R.framework/Versions/4.2-arm64/Resources/R
    

Ubuntu

Tested on Ubuntu 22.04 x86.

  • It will install the pak package under the user's directory. 'pak' supports CRAN, 'Bioconductor' and 'GitHub' packages as well.
  • It sets up a default repository.
  • It uses RSPM. So install.packages will download binary files for packages instead of building packages from their source code.
  • No sudo command before rig add release
    • But it'll ask your password anyway
    • The command will install the latest version of R. But it will not set it as the default R.
  • rig add devel will install the devel version. After I run that, rig list will show two versions of R
    $ rig --version
    RIG -- The R Installation Manager 0.5.0
    $ rig list
    * 4.2.1
      devel   (R 4.3.0)
    
  • Use sudo rig default devel to switch the default R to devel. Use sudo rig default 4.2.1 to switch back.
  • Run rig <subcommand> --help for information about a subcommand
    $ rig default --help
    $ rig rstudio --help
    $ rig system add-pak --help
    
  • Run multiple versions at the same time
    $ which R-4.2.1
    /usr/local/bin/R-4.2.1
    $ which R-devel
    /usr/local/bin/R-devel
    
  • Linux rig system subcommands
    rig system add-pak      -- install or update pak for an R version
    
  • To launch a specific version of R with RStudio (Changing R versions for the RStudio Desktop IDE)
    export RSTUDIO_WHICH_R=/opt/R/4.2.3/bin/R
    rstudio ~/Project/Project.Rproj
    
    env RSTUDIO_WHICH_R=/opt/R/4.2.3/bin/R rstudio ~/Project/Project.Rproj
    

Raspberry Pi

Tested on Raspberry Pi 3B

  • Install rig and R 4.3.0 is OK.
  • Frozen when I installed the dplyr (probably low resource).

Install Rtools for Windows users

See http://goo.gl/gYh6C for a step-by-step instruction (based on Rtools30.exe) with screenshot. Note that in the step of 'Select Components', the default is 'Package authoring installation'. But we want 'Full installation to build 32 or 64 bit R'; that is, check all components (including tcl/tk) available. The "extra" files will be stored in subdirectories of the R source home directory. These files are not needed to build packages, only to build R itself. By default, the 32-bit R source home is C:\R and 64-bit source home is C:\R64. After the installation, these two directories will contain a new directory 'Tcl'.

My preferred way is not to check the option of setting PATH environment. But I manually add the followings to the PATH environment (based on Rtools v3.2.2)

c:\Rtools\bin;
c:\Rtools\gcc-4.6.3\bin;
C:\Program Files\R\R-3.2.2\bin\i386;

We can make our life easy by creating a file <Rcommand.bat> with the content (also useful if you have C:\cygwin\bin in your PATH although cygwin setup will not do it automatically for you.)

PS. I put <Rcommand.bat> under C:\Program Files\R folder. I create a shortcut called 'Rcmd' on desktop. I enter C:\Windows\System32\cmd.exe /K "Rcommand.bat" in the Target entry and "C:\Program Files\R" in Start in entry.

@echo off
set PATH=C:\Rtools\bin;c:\Rtools\gcc-4.6.3\bin
set PATH=C:\Program Files\R\R-3.2.2\bin\i386;%PATH%
set PKG_LIBS=`Rscript -e "Rcpp:::LdFlags()"`
set PKG_CPPFLAGS=`Rscript -e "Rcpp:::CxxFlags()"`
echo Setting environment for using R
cmd

So we can open the Command Prompt anywhere and run <Rcommand.bat> to get all environment variables ready! On Windows Vista, 7 and 8, we need to run it as administrator. OR we can change the security of the property so the current user can have an executive right.

Windows Toolset

Note that R on Windows supports Mingw-w64 (not Mingw which is a separate project). See here for the issue of developing a Qt application that links against R using Rcpp. And http://qt-project.org/wiki/MinGW is the wiki for compiling Qt using MinGW and MinGW-w64.

Build R from its source on Windows OS (not cross compile on Linux)

Reference: https://cran.r-project.org/doc/manuals/R-admin.html#Installing-R-under-Windows

First we try to build 32-bit R (tested on R 3.2.2 using Rtools33). At the end I will see how to build a 64-bit R.

Download https://www.stats.ox.ac.uk/pub/Rtools/goodies/multilib/local320.zip (read https://www.stats.ox.ac.uk/pub/Rtools/libs.html). create an empty directory, say c:/R/extsoft, and unpack it in that directory by e.g.

unzip local320.zip -d c:/R/extsoft

Tcl: two methods

  1. Download tcl file from http://www.stats.ox.ac.uk/pub/Rtools/R_Tcl_8-5-8.zip. Unzip and put 'Tcl' into R_HOME folder.
  2. If you have chosen a full installation when running Rtools, then copy C:/R/Tcl or C:/R64/Tcl (not the same) to R_HOME folder.

Open a command prompt as Administrator"

set PATH=c:\Rtools\bin;c:\Rtools\gcc-4.6.3\bin
set PATH=%PATH%;C:\Users\brb\Downloads\R-3.2.2\bin\i386;c:\windows;c:\windows\system32
set TMPDIR=C:/tmp

tar --no-same-owner -xf R-3.2.2.tar.gz
cp -R c:\R64\Tcl c:\Users\brb\Downloads\R-3.2.2

cd R-3.2.2\src\gnuwin32
cp MkRules.dist MkRules.local
# Modify MkRules.local file; specifically uncomment + change the following 2 flags.
# LOCAL_SOFT = c:/R/extsoft
# EXT_LIBS = $(LOCAL_SOFT)

make

If we see an error of texi2dvi() complaining pdflatex is not available, it means a vanilla R is successfully built.

If we want to build the recommended packages (MASS, lattice, Matrix, ...) as well, run (check all make option in <R_HOME\src\gnuwin32\Makefile>)

make recommended

If we need to rebuild R for whatever reason, run

make clean

If we want to build R with debug information, run

make DEBUG=T

NB: 1. The above works for creating 32-bit R from its source. If we want to build 64-bit R from its source, we need to modify MkRules.local file to turn on the MULTI flag.

MULTI = 64

and reset the PATH variable

set PATH=c:\Rtools\bin;c:\Rtools\gcc-4.6.3\bin
set PATH=%PATH%;C:\Users\brb\Downloads\R-3.2.2\bin\x64;c:\windows;c:\windows\system32

I don't need to mess up with other flags like BINPREF64, M_ARCH, AS_ARCH, RC_ARCH, DT_ARCH or even WIN. The note http://www.stat.yale.edu/~jay/Admin3.3.pdf is kind of old and is not needed. 2. If we have already built 32-bit R and want to continue to build 64-bit R, it is not enough to run 'make clean' before run 'make' again since it will give an error message incompatible ./libR.dll.a when searching for -lR in building Rgraphapp.dll. In fact, libR.dll.a can be cleaned up if we run 'make distclean' but it will also wipe out /bin/i386 folder:(

See also Create_a_standalone_Rmath_library below about how to create and use a standalone Rmath library in your own C/C++/Fortran program. For example, if you want to know the 95-th percentile of a T distribution or generate a bunch of random variables, you don't need to search internet to find a library; you can just use Rmath library.

Build R from its source on Linux (cross compile)

Building R 4.2 for Windows with OpenBLAS

Building R 4.2 for Windows with OpenBLAS

Compile and install an R package

Command line

cd C:\Documents and Settings\brb
wget http://www.bioconductor.org/packages/2.11/bioc/src/contrib/affxparser_1.30.2.tar.gz
C:\progra~1\r\r-2.15.2\bin\R CMD INSTALL --build affxparser_1.30.2.tar.gz

N.B. the --build is used to create a binary package (i.e. affxparser_1.30.2.zip). In the above example, it will both install the package and create a binary version of the package. If we don't want the binary package, we can ignore the flag.

R console

install.packages("C:/Users/USERNAME/Downloads/DESeq2paper_1.3.tar.gz", repos=NULL, type="source")

See Chapter 6 of R Installation and Administration

Check/Upload to CRAN

http://win-builder.r-project.org/

64 bit toolchain

See January 2010 email https://stat.ethz.ch/pipermail/r-devel/2010-January/056301.html and R-Admin manual.

From R 2.11.0 there is 64 bit Windows binary for R.

Install R using binary package on Linux OS

Ubuntu/Debian

Ubuntu/Debian goodies

Since the R packages XML & RCurl & httr are frequently used by other packages (e.g. tidyverse or miniCRAN), it is useful to run the following so the install.packages("c(RCurl", "XML", "httr")) can work without hiccups.

Note that rocker/r-bspm:20.04 image already contains many *-dev libraries so I can directly use install.packages() to install XML, RCurl, httr, rgl and rgdal packages in the container.

Cairo package also requires some OS libs.

How to fix a problem: if it complains libudunits2.so.0: cannot open shared object file: No such file or directory, then we need to fix it by sudo apt-get install libudunits2-dev.

sudo apt-get update
sudo apt-get install libxml2-dev               # XML
sudo apt-get install curl libcurl4-openssl-dev # curl
sudo apt-get install libssl-dev            # httr
sudo apt install libcairo2-dev libxt-dev   # Cairo, libxt-dev includes libx11-dev
sudo apt-get install zlib1g-dev  # XVector from Bioc

# Check if a library is installed or not using "dpkg -L packageName"
# That will list all files (with location) that were brought in by the package.
dpkg -L libcurl4-openssl-dev # -L means list
dpkg -s libcurl4-openssl-dev # -s means status; useful for showing the version, depends, ...

See also

sudo apt install -q \
  libcurl4-openssl-dev \
  libssl-dev \
  libxml2-dev \
  libfontconfig1-dev \
  libharfbuzz-dev \
  libfribidi-dev \
  libfreetype6-dev \
  libpng-dev \
  libtiff5-dev \
  libjpeg-dev \
  libpq-dev

To find out the exact package names (in the situation the version number changes, not likely with these two cases: xml and curl), consider the following approach

# Search 'curl' but also highlight matches containing both 'lib' and 'dev'
> apt-cache search curl | awk '/lib/ && /dev/'
libcurl4-gnutls-dev - development files and documentation for libcurl (GnuTLS flavour)
libcurl4-nss-dev - development files and documentation for libcurl (NSS flavour)
libcurl4-openssl-dev - development files and documentation for libcurl (OpenSSL flavour)
libcurl-ocaml-dev - OCaml libcurl bindings (Development package)
libcurlpp-dev - c++ wrapper for libcurl (development files)
libflickcurl-dev - C library for accessing the Flickr API - development files
libghc-curl-dev - GHC libraries for the libcurl Haskell bindings
libghc-hxt-curl-dev - LibCurl interface for HXT
libghc-hxt-http-dev - Interface to native Haskell HTTP package HTTP
libresource-retriever-dev - Robot OS resource_retriever library - development files
libstd-rust-dev - Rust standard libraries - development files
lua-curl-dev - libcURL development files for the Lua language

If we need to install 'rgl' and related packages such as rayshader, (read here)

sudo apt install xorg 
sudo apt install libx11-dev 
sudo apt install libglu1-mesa-dev 
sudo apt install libfreetype6-dev

For 'rgdal' package, in ubuntu we need

sudo apt install libgdal-dev

RcppAPT for Ubuntu/Debian

I got an output "I'm sorry, Dave. I'm afraid I can't do that." after loading the package. I have installed libapt-pkg-dev but it does not help 😢

Major release case

BiocManager::install(version = "devel")

Uninstall R

sudo apt purge r-base* r-recommended r-cran-*
sudo apt autoremove
sudo apt update
# sudo nano /etc/apt/sources.list

Windows Subsystem for Linux

http://blog.revolutionanalytics.com/2017/12/r-in-the-windows-subsystem-for-linux.html

Redhat el6

It should be pretty easy to install via the EPEL: http://fedoraproject.org/wiki/EPEL

Just follow the instructions to enable the EPEL OR using the command line

sudo rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
sudo yum update # not sure if this is necessary

and then from the CLI:

sudo yum install R

Arch/Manjaro

https://wiki.archlinux.org/index.php/R. This method works on Garuda Linux too (Garuda Update). I got the latest R which was released a few days ago.

sudo pacman -Sy r

To install R packages, we may need to install tk first. See error: unable to load shared object '/usr/lib/R/library/tcltk/libs/tcltk.so': libtk8.6.so. We can do it by System -> Add/Remove Software menu.

To install RStudio, we need to use the Add/Remove software tool to install yay first. After that follow Step-by-step – RStudio Manjaro Installation Guide to install rstudio; i.e.

yay -S --noconfirm rstudio-desktop-bin

After that, RStudio is available under the "Development" category of the Application Launcher. rstudio binary is under /usr/lib/rstudio directory.

Install R from source (ix86, x86_64 and arm platforms, Linux system)

Debian system (focus on arm architecture with notes from x86 system)

Simplest configuration

Method 1: manually install requirements

On my debian system in Pogoplug (armv5), Raspberry Pi (armv6) OR Beaglebone Black & Udoo(armv7), I can compile R. See R's admin manual. If the OS needs x11, I just need to install 2 required packages.

  • install gfortran: apt-get install build-essential gfortran (gfortran is not part of build-essential)
  • install readline library: apt-get install libreadline5-dev (pogoplug), apt-get install libreadline6-dev (raspberry pi/BBB/Udoo dual), apt-get install libreadline-dev (Ubuntu/Udoo dual)

Note: if I need X11, I should install

  • libX11 and libX11-devel, libXt, libXt-devel (for fedora)
  • libx11-dev (for debian) or xorg-dev (for pogoplug/raspberry pi/BBB/Odroid debian/Udoo dual). See here for the difference of x11 and Xorg.

and optional

  • texinfo (to fix 'WARNING: you cannot build info or HTML versions of the R manuals')

Method 2: automatically install requirements (recommended) . Note: the apt-get build-dep command requires to enable the source repository (eg deb-src http://ports.ubuntu.com/ubuntu-ports/ trusty main universe multiverse) in /etc/apt/sources.list.

sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9
echo "deb-src https://cran.rstudio.com/bin/linux/ubuntu xenial/" | sudo tee -a /etc/apt/sources.list
sudo apt update

sudo apt-get build-dep r-base

The above command will install R dependence like jdk, tcl, tex, X11 libraries, etc. The apt-get build-dep gave a more complete list than apt-get install r-base-dev for some reasons.

[Arm architecture] I also run apt-get install readline-common. I don't know if this is necessary. If x11 is not needed or not available (eg Pogoplug), I can add --with-x=no option in ./configure command. If R will be called from other applications such as Rserve, I can add --enable-R-shlib option in ./configure command. Check out ./configure --help to get a complete list of all options.

After running

wget https://cran.rstudio.com/src/base/R-3/R-3.2.3.tar.gz
tar xzvf R-3.2.3.tar.gz
cd R-3.2.3
./configure --enable-R-shlib

(--enable-R-shlib option will create a shared R library libR.so in $RHOME/lib subdirectory. This allows R to be embedded in other applications. See Embedding R.) I got

R is now configured for armv5tel-unknown-linux-gnueabi

  Source directory:          .
  Installation directory:    /usr/local

  C compiler:                gcc -std=gnu99  -g -O2
  Fortran 77 compiler:       gfortran  -g -O2

  C++ compiler:              g++  -g -O2
  Fortran 90/95 compiler:    gfortran -g -O2
  Obj-C compiler:

  Interfaces supported:
  External libraries:        readline
  Additional capabilities:   NLS
  Options enabled:           shared R library, shared BLAS, R profiling

  Recommended packages:      yes

configure: WARNING: you cannot build info or HTML versions of the R manuals
configure: WARNING: you cannot build PDF versions of the R manuals
configure: WARNING: you cannot build PDF versions of vignettes and help pages
configure: WARNING: I could not determine a browser
configure: WARNING: I could not determine a PDF viewer

After that, we can run make to create R binary. If the computer has multiple cores, we can run make in parallel by using the -j flag (for example, '-j4' means to run 4 jobs simultaneously). We can also add time command in front of make to report the make time (useful for benchmark).

make   
# make -j4
# time make

PS 1. On my raspberry pi machine, it shows R is now configured for armv6l-unknown-linux-gnueabihf and on Beaglebone black it shows R is now configured for armv7l-unknown-linux-gnueabihf.

PS 2. Timing: On my Beaglebone black, it took 2 hours to run 'make', Raspberry Pi 2 took 1 hour, Odroid XU4 took 23 minutes and it only took 5 minutes to run 'make -j 12' on my Xeon W3690 @ 3.47Ghz (6 cores with hyperthread) based on R 3.1.2. Udoo dual took 82 m on R 4.3.1.

PS 3. On my x86 system, it shows

R is now configured for x86_64-unknown-linux-gnu

  Source directory:          .
  Installation directory:    /usr/local

  C compiler:                gcc -std=gnu99  -g -O2
  Fortran 77 compiler:       gfortran  -g -O2

  C++ compiler:              g++  -g -O2
  Fortran 90/95 compiler:    gfortran -g -O2
  Obj-C compiler:

  Interfaces supported:      X11, tcltk
  External libraries:        readline, lzma
  Additional capabilities:   PNG, JPEG, TIFF, NLS, cairo
  Options enabled:           shared R library, shared BLAS, R profiling, Java

  Recommended packages:      yes

[arm] However, make gave errors for recommanded packages like KernSmooth, MASS, boot, class, cluster, codetools, foreign, lattice, mgcv, nlme, nnet, rpart, spatial, and survival. The error stems from gcc: SHLIB_LIBADD: No such file or directory. Note that I can get this error message even I try install.packages("MASS", type="source"). A suggested fix is here; adding perl = TRUE in sub() call for two lines in src/library/tools/R/install.R file. However, I got another error shared object 'MASS.so' not found. See also http://ftp.debian.org/debian/pool/main/r/r-base/. To build R without recommended packages like ./configure --without-recommended.

make[1]: Entering directory `/mnt/usb/R-2.15.2/src/library/Recommended'
make[2]: Entering directory `/mnt/usb/R-2.15.2/src/library/Recommended'
begin installing recommended package MASS
* installing *source* package 'MASS' ...
** libs
make[3]: Entering directory `/tmp/Rtmp4caBfg/R.INSTALL1d1244924c77/MASS/src'
gcc -std=gnu99 -I/mnt/usb/R-2.15.2/include -DNDEBUG  -I/usr/local/include    -fpic  -g -O2  -c MASS.c -o MASS.o
gcc -std=gnu99 -I/mnt/usb/R-2.15.2/include -DNDEBUG  -I/usr/local/include    -fpic  -g -O2  -c lqs.c -o lqs.o
gcc -std=gnu99 -shared -L/usr/local/lib -o MASSSHLIB_EXT MASS.o lqs.o SHLIB_LIBADD -L/mnt/usb/R-2.15.2/lib -lR
gcc: SHLIB_LIBADD: No such file or directory
make[3]: *** [MASSSHLIB_EXT] Error 1
make[3]: Leaving directory `/tmp/Rtmp4caBfg/R.INSTALL1d1244924c77/MASS/src'
ERROR: compilation failed for package 'MASS'
* removing '/mnt/usb/R-2.15.2/library/MASS'
make[2]: *** [MASS.ts] Error 1
make[2]: Leaving directory `/mnt/usb/R-2.15.2/src/library/Recommended'
make[1]: *** [recommended-packages] Error 2
make[1]: Leaving directory `/mnt/usb/R-2.15.2/src/library/Recommended'
make: *** [stamp-recommended] Error 2
root@debian:/mnt/usb/R-2.15.2#
root@debian:/mnt/usb/R-2.15.2# bin/R

R version 2.15.2 (2012-10-26) -- "Trick or Treat"
Copyright (C) 2012 The R Foundation for Statistical Computing
ISBN 3-900051-07-0
Platform: armv5tel-unknown-linux-gnueabi (32-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.

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.

> library(MASS)
Error in library(MASS) : there is no package called 'MASS'
> library()
Packages in library '/mnt/usb/R-2.15.2/library':

base                    The R Base Package
compiler                The R Compiler Package
datasets                The R Datasets Package
grDevices               The R Graphics Devices and Support for Colours
                        and Fonts
graphics                The R Graphics Package
grid                    The Grid Graphics Package
methods                 Formal Methods and Classes
parallel                Support for Parallel computation in R
splines                 Regression Spline Functions and Classes
stats                   The R Stats Package
stats4                  Statistical Functions using S4 Classes
tcltk                   Tcl/Tk Interface
tools                   Tools for Package Development
utils                   The R Utils Package
> Sys.info()["machine"]
   machine
"armv5tel"
> gc()
         used (Mb) gc trigger (Mb) max used (Mb)
Ncells 170369  4.6     350000  9.4   350000  9.4
Vcells 163228  1.3     905753  7.0   784148  6.0

See http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=679180

PS 4. The complete log of building R from source is in here File:Build R log.txt

Full configuration

  Interfaces supported:      X11, tcltk
  External libraries:        readline, curl
  Additional capabilities:   PNG, JPEG, TIFF, NLS, cairo, ICU
  Options enabled:           shared R library, shared BLAS, R profiling, Java

configure: error: libcurl >= 7.XX.0 library and headers are required with support for https

See here. I need to remove anaconda3/bin from the PATH variable (export PATH=....).

Install R without support for long doubles (noLD) on Ubuntu

Install R without support for long doubles (noLD) on Ubuntu

ARM

Options to install R on a Raspberry Pi and other ARM systems 2023

Update: R 3.0.1 on Beaglebone Black (armv7a) + Ubuntu 13.04

See the page here.

Update: R 3.1.3 & R 3.2.0 on Raspberry Pi 2

It took 134m to run 'make -j 4' on RPi 2 using R 3.1.3.

But I got an error when I ran './configure; make -j 4' using R 3.2.0. The errors start from compiling <main/connections.c> file with 'undefined reference to ....'. The gcc version is 4.6.3.

R 4.0.3 on Raspberry pi zero w

make[2]: Leaving directory '/home/pi/R-4.0.3/src/library/Recommended'
make[1]: Leaving directory '/home/pi/R-4.0.3/src/library/Recommended'
make[1]: Entering directory '/home/pi/R-4.0.3/src/library'
building/updating vignettes for package 'grid' ...
building/updating vignettes for package 'parallel' ...
building/updating vignettes for package 'utils' ...
make[1]: Leaving directory '/home/pi/R-4.0.3/src/library'
make[1]: Entering directory '/home/pi/R-4.0.3'
configuring Java ...
Java interpreter : /usr/bin/java
Error occurred during initialization of VM
Server VM is only supported on ARMv7+ VFP

*** Java interpreter doesn't work properly.

make[1]: [Makefile:88: stamp-java] Error 1 (ignored)
make[1]: Leaving directory '/home/pi/R-4.0.3'

Udoo and PCRE2

UDoo dual (released 2013) comes with Ubuntu 14.04 (released 2018). When I install R 4.3.1, the .configure commands complains about missing PCRE2 library. The apt-get install libpcre2-dev command cannot find the library. So we need to install PCRE2 from source. After that, ./configure and make commands work fine.

wget https://github.com/PCRE2Project/pcre2/releases/download/pcre2-10.42/pcre2-10.42.tar.gz
tar -zxvf pcre2-10.42.tar.gz
cd pcre2-10.42
./configure
make -j 2
sudo make install

Odroid xu4 + Ubuntu 18.04

Ubuntu 18.04.3 (20190910) (MINIMAL, BARE OS)

PS: https://hub.docker.com/_/r-base/ provides arm64 image but not arm32.

sudo apt-get install build-essential gfortran
sudo apt-get install libreadline-dev
sudo apt install libx11-dev
sudo apt install texinfo
sudo apt install zlib1g-dev
sudo apt install libpcre2-dev
# sudo apt install libcurl-dev
sudo apt install libcurl4-openssl-dev
sudo apt install libbz2-dev
sudo apt install liblzma-dev
sudo apt install default-jdk
sudo apt install wget
tar -xzvf Downloads/R-4.0.1.tar.gz
cd R-4.0.1/
./configure --enable-R-shlib
# R is now configured for armv7l-unknown-linux-gnueabihf
time make -j4  # 34m on host, 20m in Docker

I also tested it on docker debian:buster image.

Raspbian stretch on Pi or ARM based SBC

Edit /etc/apt/sources.list and add the following 2 lines

deb http://mirrordirector.raspbian.org/raspbian/ stretch main contrib non-free rpi
deb-src http://mirrordirector.raspbian.org/raspbian/ stretch main contrib non-free rpi

PS. On Odroid Ubuntu 18.04, apt-cache show r-base shows r-base is in "universe/math" section.

Now it is ready to run sudo apt-get build-dep r-base. Note that this will install lots of packages:

pi@raspberrypi:~ $ sudo apt-get build-dep r-base
Reading package lists... Done
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following NEW packages will be installed:
  adwaita-icon-theme autoconf automake autopoint autotools-dev bison ca-certificates-java dconf-gsettings-backend
  dconf-service debhelper default-jdk default-jdk-headless default-jre default-jre-headless dh-autoreconf
  dh-strip-nondeterminism fontconfig fontconfig-config fonts-cabin fonts-comfortaa fonts-croscore
  fonts-crosextra-caladea fonts-crosextra-carlito fonts-dejavu-core fonts-dejavu-extra fonts-ebgaramond
  fonts-ebgaramond-extra fonts-font-awesome fonts-freefont-otf fonts-freefont-ttf fonts-gfs-artemisia
  fonts-gfs-complutum fonts-gfs-didot fonts-gfs-neohellenic fonts-gfs-olga fonts-gfs-solomos fonts-junicode
  fonts-lato fonts-linuxlibertine fonts-lmodern fonts-lobster fonts-lobstertwo fonts-noto-hinted
  fonts-oflb-asana-math fonts-roboto-hinted fonts-sil-gentium fonts-sil-gentium-basic fonts-sil-gentiumplus
  fonts-sil-gentiumplus-compact fonts-stix gettext gfortran gfortran-6 gir1.2-freedesktop gir1.2-glib-2.0
  gir1.2-pango-1.0 glib-networking glib-networking-common glib-networking-services gsettings-desktop-schemas
  gtk-update-icon-cache hicolor-icon-theme icu-devtools intltool-debian java-common libarchive-zip-perl libasyncns0
  libatk-bridge2.0-0 libatk-wrapper-java libatk-wrapper-java-jni libatk1.0-0 libatk1.0-data libatspi2.0-0
  libavahi-client3 libbison-dev libblas-common libblas-dev libblas3 libbz2-dev libcairo-gobject2
  libcairo-script-interpreter2 libcairo2 libcairo2-dev libcolord2 libcroco3 libcups2 libcupsimage2
  libcurl4-openssl-dev libdatrie1 libdconf1 libepoxy0 libexpat1-dev libfile-stripnondeterminism-perl libflac8
  libfontconfig1 libfontconfig1-dev libfontenc1 libgdk-pixbuf2.0-0 libgdk-pixbuf2.0-common libgfortran-6-dev
  libgfortran3 libgif7 libgirepository-1.0-1 libgl1-mesa-glx libglapi-mesa libglib2.0-bin libglib2.0-dev
  libgraphite2-3 libgraphite2-dev libgs9 libgs9-common libgtk-3-0 libgtk-3-common libgtk2.0-0 libgtk2.0-common
  libharfbuzz-dev libharfbuzz-gobject0 libharfbuzz-icu0 libharfbuzz0b libice-dev libice6 libicu-dev libijs-0.35
  libjbig-dev libjbig0 libjbig2dec0 libjpeg-dev libjpeg62-turbo-dev libjson-glib-1.0-0 libjson-glib-1.0-common
  libkpathsea6 liblapack-dev liblapack3 liblcms2-2 liblzma-dev libncurses5-dev libnspr4 libnss3 libogg0 libopenjp2-7
  libpango-1.0-0 libpango1.0-dev libpangocairo-1.0-0 libpangoft2-1.0-0 libpangoxft-1.0-0 libpaper-utils libpaper1
  libpcre16-3 libpcre3-dev libpcre32-3 libpcrecpp0v5 libpixman-1-0 libpixman-1-dev libpoppler64 libpotrace0
  libproxy1v5 libptexenc1 libpthread-stubs0-dev libpulse0 libreadline-dev librest-0.7-0 librsvg2-2 librsvg2-common
  libsm-dev libsm6 libsndfile1 libsoup-gnome2.4-1 libsoup2.4-1 libsynctex1 libtcl8.6 libtexlua52 libtexluajit2
  libtext-unidecode-perl libthai-data libthai0 libtiff5 libtiff5-dev libtiffxx5 libtinfo-dev libtk8.6 libtool
  libvorbis0a libvorbisenc2 libx11-dev libx11-xcb1 libxau-dev libxaw7 libxcb-dri2-0 libxcb-dri3-0 libxcb-glx0
  libxcb-present0 libxcb-render0 libxcb-render0-dev libxcb-shape0 libxcb-shm0 libxcb-shm0-dev libxcb-sync1
  libxcb1-dev libxcomposite1 libxcursor1 libxdamage1 libxdmcp-dev libxext-dev libxfixes3 libxfont1 libxfont2
  libxft-dev libxft2 libxi6 libxinerama1 libxkbfile1 libxml-libxml-perl libxml-namespacesupport-perl
  libxml-sax-base-perl libxml-sax-perl libxmu6 libxpm4 libxrandr2 libxrender-dev libxrender1 libxshmfence1 libxss-dev
  libxss1 libxt-dev libxt6 libxtst6 libxv1 libxxf86dga1 libxxf86vm1 libzzip-0-13 m4 mpack openjdk-8-jdk
  openjdk-8-jdk-headless openjdk-8-jre openjdk-8-jre-headless po-debconf poppler-data preview-latex-style t1utils
  tcl8.6 tcl8.6-dev tex-common texinfo texlive-base texlive-binaries texlive-extra-utils texlive-fonts-extra
  texlive-fonts-recommended texlive-generic-recommended texlive-latex-base texlive-latex-extra
  texlive-latex-recommended texlive-pictures tk8.6 tk8.6-dev ttf-adf-accanthis ttf-adf-gillius ttf-adf-universalis
  x11-common x11-utils x11-xkb-utils x11proto-core-dev x11proto-input-dev x11proto-kb-dev x11proto-render-dev
  x11proto-scrnsaver-dev x11proto-xext-dev xdg-utils xfonts-base xfonts-encodings xfonts-utils xorg-sgml-doctools
  xserver-common xtrans-dev xvfb
0 upgraded, 276 newly installed, 0 to remove and 0 not upgraded.
Need to get 518 MB of archives.
After this operation, 1,578 MB of additional disk space will be used.
Do you want to continue? [Y/n] n
$ ./configure --with-x=no
$ time make
...
make[1]: Leaving directory '/home/pi/R-3.5.1'

real	213m9.985s
user	206m50.825s
sys	3m23.482s

Setting up your own shiny-server / rstudio-server on a Raspberry Pi 3B+

Some bash script used on Designing a Raspberry Pi Based Intelligent Ultrasonic Bat Detector App article

Install all dependencies for building R

This is a comprehensive list. This list is even larger than r-base-dev.

root@debian:/mnt/usb/R-2.15.2# apt-get build-dep r-base
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be REMOVED:
  libreadline5-dev
The following NEW packages will be installed:
  bison ca-certificates ca-certificates-java debhelper defoma ed file fontconfig gettext
  gettext-base html2text intltool-debian java-common libaccess-bridge-java
  libaccess-bridge-java-jni libasound2 libasyncns0 libatk1.0-0 libaudit0 libavahi-client3
  libavahi-common-data libavahi-common3 libblas-dev libblas3gf libbz2-dev libcairo2
  libcairo2-dev libcroco3 libcups2 libdatrie1 libdbus-1-3 libexpat1-dev libflac8
  libfontconfig1-dev libfontenc1 libfreetype6-dev libgif4 libglib2.0-dev libgtk2.0-0
  libgtk2.0-common libice-dev libjpeg62-dev libkpathsea5 liblapack-dev liblapack3gf libnewt0.52
  libnspr4-0d libnss3-1d libogg0 libopenjpeg2 libpango1.0-0 libpango1.0-common libpango1.0-dev
  libpcre3-dev libpcrecpp0 libpixman-1-0 libpixman-1-dev libpng12-dev libpoppler5 libpulse0
  libreadline-dev libreadline6-dev libsm-dev libsndfile1 libthai-data libthai0 libtiff4-dev
  libtiffxx0c2 libunistring0 libvorbis0a libvorbisenc2 libxaw7 libxcb-render-util0
  libxcb-render-util0-dev libxcb-render0 libxcb-render0-dev libxcomposite1 libxcursor1
  libxdamage1 libxext-dev libxfixes3 libxfont1 libxft-dev libxi6 libxinerama1 libxkbfile1
  libxmu6 libxmuu1 libxpm4 libxrandr2 libxrender-dev libxss-dev libxt-dev libxtst6 luatex m4
  openjdk-6-jdk openjdk-6-jre openjdk-6-jre-headless openjdk-6-jre-lib openssl pkg-config
  po-debconf preview-latex-style shared-mime-info tcl8.5-dev tex-common texi2html texinfo
  texlive-base texlive-binaries texlive-common texlive-doc-base texlive-extra-utils
  texlive-fonts-recommended texlive-generic-recommended texlive-latex-base texlive-latex-extra
  texlive-latex-recommended texlive-pictures tk8.5-dev tzdata-java whiptail x11-xkb-utils
  x11proto-render-dev x11proto-scrnsaver-dev x11proto-xext-dev xauth xdg-utils xfonts-base
  xfonts-encodings xfonts-utils xkb-data xserver-common xvfb zlib1g-dev
0 upgraded, 136 newly installed, 1 to remove and 0 not upgraded.
Need to get 139 MB of archives.
After this operation, 410 MB of additional disk space will be used.
Do you want to continue [Y/n]?

Instruction of installing a development version of R under Ubuntu

https://github.com/wch/r-source/wiki (works on Ubuntu 12.04)

Note that texi2dvi has to be installed first to avoid the following error. It is better to follow the Ubuntu instruction (https://github.com/wch/r-source/wiki/Ubuntu-build-instructions) when we work on Ubuntu OS.

$ (cd doc/manual && make front-matter html-non-svn)
creating RESOURCES
/bin/bash: number-sections: command not found
make: [../../doc/RESOURCES] Error 127 (ignored)

To build R, run the following script. To run the built R, type 'bin/R'.

# Get recommended packages if necessary
tools/rsync-recommended

R_PAPERSIZE=letter                              \
R_BATCHSAVE="--no-save --no-restore"            \
R_BROWSER=xdg-open                              \
PAGER=/usr/bin/pager                            \
PERL=/usr/bin/perl                              \
R_UNZIPCMD=/usr/bin/unzip                       \
R_ZIPCMD=/usr/bin/zip                           \
R_PRINTCMD=/usr/bin/lpr                         \
LIBnn=lib                                       \
AWK=/usr/bin/awk                                \
CC="ccache gcc"                                 \
CFLAGS="-ggdb -pipe -std=gnu99 -Wall -pedantic" \
CXX="ccache g++"                                \
CXXFLAGS="-ggdb -pipe -Wall -pedantic"          \
FC="ccache gfortran"                            \
F77="ccache gfortran"                           \
MAKE="make"                                     \
./configure                                     \
    --prefix=/usr/local/lib/R-devel             \
    --enable-R-shlib                            \
    --with-blas                                 \
    --with-lapack                               \
    --with-readline

#CC="clang -O3"                                  \
#CXX="clang++ -03"                               \


# Workaround for explicit SVN check introduced by
# https://github.com/wch/r-source/commit/4f13e5325dfbcb9fc8f55fc6027af9ae9c7750a3

# Need to build FAQ
(cd doc/manual && make front-matter html-non-svn)

rm -f non-tarball

# Get current SVN revsion from git log and save in SVN-REVISION
echo -n 'Revision: ' > SVN-REVISION
git log --format=%B -n 1 \
  | grep "^git-svn-id" \
  | sed -E 's/^git-svn-id: https:\/\/svn.r-project.org\/R\/.*?@([0-9]+).*$/\1/' \
  >> SVN-REVISION
echo -n 'Last Changed Date: ' >>  SVN-REVISION
git log -1 --pretty=format:"%ad" --date=iso | cut -d' ' -f1 >> SVN-REVISION

# End workaround

# Set this to the number of cores on your computer
make --jobs=4

If we DO NOT use -depth option in git clone command, we can use git checkout SHA1 (40 characters) to get a certain version of code.

git checkout f1d91a0b34dbaa6ac807f3852742e3d646fbe95e  # plot(<dendrogram>): Bug 15215 fixed 5/2/2015
git checkout trunk                                     # switch back to trunk

The svn revision number for a certain git revision can be found in the blue box on the github website (git-svn-id). For example, this revision has an svn revision number 68302 even the current trunk is 68319.

Now suppose we have run 'git check trunk', create a devel'R successfully. If we want to build R for a certain svn or git revision, we run 'git checkout SHA1', 'make distclean', code to generate the SVN-REVISION file (it will update this number) and finally './configure' & 'make'.

time (./configure --with-recommended-packages=no && make --jobs=5)

The timing is 4m36s if I skip recommended packages and 7m37s if I don't skip. This is based on Xeon W3690 @ 3.47GHz.

The full bash script is available on Github Gist.

Install multiple versions of R on Ubuntu

  • (2023/10/5) I compiled an earlier version of R from source (for some earlier projects) and this is useful when I set up an renv environment for that project which depends on an earlier version of R. For convenience I put an alias in "~/.bashrc" file. The alias looks like
alias R42='~/R/R-4.2.3/bin/R'
  • When installing a binary version of R through apt install, the default R/Rscript location is /usr/bin.
  • Install multiple versions of R from precompiled binaries on a Linux server. These precompiled binaries are provided by RStudio.
    • The precompiled binaries are available for RHEL/CentOS, Ubuntu/Debian
    • It supports multiple versions of R
    • For example, the binary executable for R 4.2.3 is located at /opt/R/4.2.3/bin/R
  • Installing multiple versions of R on Linux especially on RStudio Server, Mar 13, 2018.
    • Some common locations are /usr/lib/R/bin, /usr/local/bin (create softlinks for the binaries here), /usr/bin.
    • When build R from source, specify prefix.
$ ./configure --prefix=/opt/R/3.5.0 --enable-R-shlib
$ time make -j10             # 4m14s on E5-1650 @ 3.2GHz
$ sudo make install          # check /opt/R/3.5.0 directory

# Run the following 2 lines to make this version of R as default so RStudio IDE can detect R.

$ sudo rm /usr/bin/R /usr/bin/Rscript
$ sudo ln /opt/R/3.5.0/bin/R /usr/bin/R 
$ sudo ln /opt/R/3.5.0/bin/Rscript /usr/bin/Rscript
$ ls -l /usr/bin/R           # Did not show it's a soft link
$ diff bin/R /usr/bin/R 
$ which R
$ tree -L 3 /opt/R/3.5.0/
/opt/R/3.5.0/
├── bin
│   ├── R
│   └── Rscript
├── lib
│   ├── pkgconfig
│   │   └── libR.pc
│   └── R
│       ├── bin
│       ├── COPYING
│       ├── doc
│       ├── etc
│       ├── include
│       ├── lib
│       ├── library
│       ├── modules
│       ├── share
│       └── SVN-REVISION
└── share
    └── man
        └── man1

To install the devel version of R alongside the current version of R. See this post. For example you need a script that will build r-devel, but install it in a location different from the stable version of R (eg use --prefix=/usr/local/R-X.Y.Z in the config command). Note that the executable is installed in “/usr/local/lib/R-devel/bin”, but that can be changed to others like "/usr/local/bin".

Another fancy way is to use docker.

Minimal installation of R from source

Assume we have installed g++ (or build-essential) and gfortran (Ubuntu has only gcc pre-installed, but not g++),

sudo apt-get install build-essential gfortran

we can go ahead to build a minimal R.

wget http://cran.rstudio.com/src/base/R-3/R-3.1.1.tar.gz
tar -xzvf R-3.1.1.tar.gz; cd R-3.1.1
./configure --with-x=no --with-recommended-packages=no --with-readline=no

See ./configure --help. This still builds the essential packages like base, compiler, datasets, graphics, grDevices, grid, methods, parallel, splines, stats, stats4, tcltk, tools, and utils.

Note that at the end of 'make', it shows an error of 'cannot find any java interpreter. Please make sure java is on your PATH or set JAVA_HOME correspondingly'. Even with the error message, we can use R by typing bin/R.

To check whether we have Java installed, type 'java -version'.

$ java -version
java version "1.6.0_32"
OpenJDK Runtime Environment (IcedTea6 1.13.4) (6b32-1.13.4-4ubuntu0.12.04.2)
OpenJDK 64-Bit Server VM (build 23.25-b01, mixed mode)

Recommended packages

Supported Packages

R can be installed without recommended packages. Keep it in mind. Some people have assumed that a `recommended' package can safely be used unconditionally, but this is not so.

https://github.com/wch/r-source/tree/trunk/src/library

$ docker run --net=host -it --rm r-base # 3.6.3

> .libPaths()
> x <- library(lib.loc = '/usr/lib/R/library')
> class(x)  # [1] "libraryIQR"
> x$results[, "Package"]
 [1] "base"       "boot"       "class"      "cluster"    "codetools"
 [6] "compiler"   "datasets"   "foreign"    "graphics"   "grDevices"
[11] "grid"       "KernSmooth" "lattice"    "MASS"       "Matrix"
[16] "methods"    "mgcv"       "nlme"       "nnet"       "parallel"
[21] "rpart"      "spatial"    "splines"    "stats"      "stats4"
[26] "survival"   "tcltk"      "tools"      "utils"

Run R commands on bash terminal

http://pacha.hk/2017-10-20_r_on_ubuntu_17_10.html

# Install R
sudo apt-get update
sudo apt-get install gdebi libxml2-dev libssl-dev libcurl4-openssl-dev r-base r-base-dev

# install common packages
R --vanilla << EOF
install.packages(c("tidyverse","data.table","dtplyr","devtools","roxygen2"), repos = "https://cran.rstudio.com/")
q()
EOF

# Export to HTML/Excel
R --vanilla << EOF
install.packages(c("htmlTable","openxlsx"), repos = "https://cran.rstudio.com/")
q()
EOF# Blog tools
R --vanilla << EOF
install.packages(c("knitr","rmarkdown"), repos='http://cran.us.r-project.org')
q()
EOF

R CMD

  • R CMD build someDirectory - create a package
  • R CMD check somePackage_1.2-3.tar.gz - check a package
  • R CMD INSTALL somePackage_1.2-3.tar.gz - install a package from its source

bin/R (shell script) and bin/exec/R (binary executable) on Linux OS

bin/R is just a shell script to launch bin/exec/R program. So if we try to run the following program

# test.R
cat("-- reading arguments\n", sep = "");
cmd_args = commandArgs();
for (arg in cmd_args) cat("  ", arg, "\n", sep="");

from command line like

$ R --slave --no-save --no-restore --no-environ --silent --args arg1=abc < test.R
# OR using Rscript
-- reading arguments
  /home/brb/R-3.0.1/bin/exec/R
  --slave
  --no-save
  --no-restore
  --no-environ
  --silent
  --args
  arg1=abc

we can see R actually call bin/exec/R program.

CentOS 6.x

Install build-essential (make, gcc, gdb, ...).

su
yum groupinstall "Development Tools"
yum install kernel-devel kernel-headers

Install readline and X11 (probably not necessary if we use ./configure --with-x=no)

yum install readline-devel 
yum install libX11 libX11-devel libXt libXt-devel

Install libpng (already there) and libpng-devel library. This is for web application purpose because png (and possibly svg) is a standard and preferred graphics format. If we want to output different graphics formats, we have to follow the guide in R-admin manual to install extra graphics libraries in Linux.

yum install libpng-devel
rpm -qa | grep "libpng"
# make sure both libpng and libpng-devel exist.

Install Java. One possibility is to download from Oracle. We want to download jdk-7u45-linux-x64.rpm and jre-7u45-linux-x64.rpm (assume 64-bit OS).

rpm -Uvh jdk-7u45-linux-x64.rpm
rpm -Uvh jre-7u45-linux-x64.rpm
# Check
java -version

Now we are ready to build R by using "./configure" and then "make" commands.

We can make R accessible from any directory by either run "make install" command or creating an R_HOME environment variable and export it to PATH environment variable, such as

export R_HOME="path to R"
export PATH=$PATH:$R_HOME/bin 

Install R on Mac

http://mac.r-project.org/. The website has nightly build of r-devel binary too. Just untar to use it without any docker or vagrant.

The installer is called "R-4.1.0.pkg" for R 4.1.0. The installation asked me for the password.

Noted that personal R packages will be installed to ~/Library/R directory. More specifically, packages from R 3.3.x will be installed onto ~/Library/R/3.3/library.

For R 3.4.x, the R packages go to /Library/Frameworks/R.framework/Versions/3.4/Resources/library. The advantages of using this folder is 1. the folder is writable by anyone. 2. even the built-in packages can be upgraded by users.

InstallRonMac.png

$ ls -l /Library/Frameworks/R.framework/
total 0
lrwxr-xr-x  1 root  admin   24 Feb 19 10:11 Headers -> Versions/Current/Headers
lrwxr-xr-x  1 root  admin   30 Feb 19 10:11 Libraries -> Versions/Current/Resources/lib
lrwxr-xr-x  1 root  admin   31 Feb 19 10:11 PrivateHeaders -> Versions/Current/PrivateHeaders
lrwxr-xr-x  1 root  admin   18 Feb 19 10:11 R -> Versions/Current/R
lrwxr-xr-x  1 root  admin   26 Feb 19 10:11 Resources -> Versions/Current/Resources
drwxrwxr-x  7 root  admin  224 Feb 19 10:11 Versions
$ ls -l /Library/Frameworks/R.framework/Versions/
total 0
drwxrwxr-x  6 root  admin  192 Apr 16  2017 3.3
drwxrwxr-x  4 root  admin  128 Jun  7  2018 3.4
drwxrwxr-x  6 root  admin  192 Feb 19 10:11 3.5
lrwxr-xr-x  1 root  admin    3 Feb 19 10:11 Current -> 3.5
$ ls -l /Library/Frameworks/R.framework/Versions/3.5
total 0
lrwxr-xr-x   1 root  admin    17 Feb 19 10:11 Headers -> Resources/include
drwxrwxr-x  32 root  admin  1024 Feb 19 10:11 PrivateHeaders
lrwxr-xr-x   1 root  admin    24 Feb 19 10:11 R -> Resources/lib/libR.dylib
drwxrwxr-x  18 root  admin   576 Feb 19 10:11 Resources
$ ls /Library/Frameworks/R.framework/Versions/3.5/Resources/
COPYING		Rscript		doc		include		man1		tests
Info.plist	SVN-REVISION	etc		lib		modules
R		bin		fontconfig	library		share
$ ls /Library/Frameworks/R.framework/Versions/3.5/Resources/bin
BATCH		REMOVE		Rprof		build		javareconf	rtags
COMPILE		Rcmd		Rscript		check		libtool
INSTALL		Rd2pdf		SHLIB		config		mkinstalldirs
LINK		Rdconv		Stangle		exec		pager
R		Rdiff		Sweave		f77_f2c		qpdf
$ ls /Library/Frameworks/R.framework/Versions/3.5/Resources/library/
$ pkgutil --pkgs | grep r-project
org.r-project.R.el-capitan.fw.pkg
org.r-project.x86_64.tcltk.x11
org.r-project.x86_64.clang6
org.r-project.x86_64.texinfo
org.r-project.R.mavericks.fw.pkg
org.r-project.R.mavericks.GUI.pkg
org.r-project.R.el-capitan.GUI.pkg
$ sudo pkgutil --forget org.r-project.R.el-capitan.fw.pkg
Password:
Forgot package 'org.r-project.R.el-capitan.fw.pkg' on '/'.
# Then press the 'Continue' button (see the first screen shot) when I install R 3.6.0

# At the end, R 3.5.x is kept after R 3.6.0 is installed

$ ls -l /Library/Frameworks/R.framework/Versions/3.4
total 0
drwxrwxr-x  4 root  admin  128 Jun  7  2018 Resources
$ ls -l /Library/Frameworks/R.framework/Versions/3.5
total 0
lrwxr-xr-x   1 root  admin    17 Feb 19 10:11 Headers -> Resources/include
drwxrwxr-x  32 root  admin  1024 Feb 19 10:11 PrivateHeaders
lrwxr-xr-x   1 root  admin    24 Feb 19 10:11 R -> Resources/lib/libR.dylib
drwxrwxr-x  18 root  admin   576 Feb 19 10:11 Resources
$ ls -l /Library/Frameworks/R.framework/Versions/3.6
total 0
lrwxr-xr-x   1 root  admin    17 May  3 19:49 Headers -> Resources/include
drwxrwxr-x  32 root  admin  1024 Apr 26 12:39 PrivateHeaders
lrwxr-xr-x   1 root  admin    24 May  3 19:49 R -> Resources/lib/libR.dylib
drwxrwxr-x  18 root  admin   576 May  3 19:50 Resources

# However, running "/Library/Frameworks/R.framework/Versions/3.5/Resources/bin/R" 
# still launches 3.6.0 R?

M1

Fully Native M1/Apple Silicon R Setup

Multiple versions

How do I run multiple versions of R on macOS X 12+ without RStudio Workbench or rswitch?

If we use the new pkg installer to install another version of R, the original version of R will become "incomplete" and be greyed out (see a screenshot) when we click on the RSwitch app (see the next section).

Installing multiple parallel versions of R on Mac and getting back up and running quickly by simplifying package installation. In fact, when we use the pkg installer to install R, the GUI already tells how to keep the current version of R.

So when the R installer reminds me to run "sudo pkgutil --forget org.R-project.R.fw.pkg", go ahead and do it in a Terminal BEFORE I continue the installation process.

sudo pkgutil --forget org.R-project.R.fw.pkg

ls -l /Library/Frameworks/R.framework/Versions/

install-rstats - Install various versions of R on macOS and Windows.

My solution

I currently have multiple version of R but some versions are incomplete.

$ ls /Library/Frameworks/R.framework/Versions                                                          
3.5     3.6     4.0     4.1     4.2     Current
$ tree -L 2 /Library/Frameworks/R.framework/Versions                                                              13:36:20
/Library/Frameworks/R.framework/Versions
├── 3.5
│   └── Resources
├── 3.6
│   ├── Headers -> Resources/include
│   ├── PrivateHeaders
│   ├── R -> Resources/lib/libR.dylib
│   └── Resources
├── 4.0
│   ├── Headers -> Resources/include
│   ├── PrivateHeaders
│   ├── R -> Resources/lib/libR.dylib
│   └── Resources
├── 4.1
│   └── Resources
├── 4.2
│   ├── Headers -> Resources/include
│   ├── PrivateHeaders
│   ├── R -> Resources/lib/libR.dylib
│   └── Resources
└── Current -> 4.2

As you can see below, no matter it is the version specific or the global version of R, it always points to the same location.

Global version

$ which R                                                                                    
/usr/local/bin/R
$ ls -l /usr/local/bin/R
/usr/local/bin/R -> /Library/Frameworks/R.framework/Resources/bin/R

$ head  /Library/Frameworks/R.framework/Resources/bin/R                                             
#!/bin/sh
# Shell wrapper for R executable.

R_HOME_DIR=/Library/Frameworks/R.framework/Resources

Version 3.6

$ head /Library/Frameworks/R.framework/Versions/3.6/Resources/bin/R
#!/bin/sh
# Shell wrapper for R executable.

R_HOME_DIR=/Library/Frameworks/R.framework/Resources

So a simple solution is to comment out the line about R_HOME_DIR and replace it with R_HOME_DIR=/Library/Frameworks/R.framework/Versions/3.6/Resources. Then I can launch R 3.6.X by calling

$ /Library/Frameworks/R.framework/Versions/3.6/Resources/bin/R

RSwitch

https://rud.is/rswitch/

Once run the app, it will create a new icon on the menubar.

The source code website said we need to use the “tar.gz” versions of R from the R for macOS Developer's Page since the official CRAN binary installers clean up after themselves quite nicely to prevent potentially wacky behavior.

But so far I am able to switch between R 3.6.0 and 4.0.0 even I have installed the binary versions of R. Note that if I switch to R 4.0.0, then even I run /Library/Frameworks/R.framework/Versions/3.6/Resources/R, it still launches R 4.0.0. Same thing happens in the other way too. The reason is explained in the following terminal output and Changing R versions for RStudio desktop.

mac$ which R
/usr/local/bin/R
mac$ ls -l /usr/local/bin/R
lrwxr-xr-x  1 root  admin  47 Apr 25 16:35 /usr/local/bin/R -> /Library/Frameworks/R.framework/Resources/bin/R

mac$ ls -l /Library/Frameworks/R.framework/Versions/           17:18:00
total 0
drwxrwxr-x  3 root     admin   96 Jun 12  2019 3.5
drwxrwxr-x  6 root     admin  192 Jun 12  2019 3.6
drwxrwxr-x  6 root     admin  192 Apr 25 16:35 4.0
lrwxr-xr-x  1 USERNAME admin   44 Apr 25 17:25 Current -> /Library/Frameworks/R.framework/Versions/4.0

Clang

https://cran.rstudio.com/bin/macosx/tools/

This package will install clang 6.0.0 for OS X 10.11 (El Capitan) or higher with OpenMP support in /usr/local/clang6

In order to use this compiler you have to add /usr/local/clang6/bin to the PATH environment variable such as 
export PATH=/usr/local/clang6/bin:$PATH or modify ~/.bash_profile file by adding a new line PATH=/usr/local/clang6/bin:$PATH.

'stdlib.h' file not found

When I use R's inline package by running this example to generate random numbers, I got the following error!

R > library(inline)
R > src <- "\nGetRNGstate();\ndouble u = unif_rand();\nRprintf(\"%f\\n\", u);\nPutRNGstate();\nreturn R_NilValue;\n"
R > fun <- cxxfunction(signature(), body = src)
R > # set.seed(1); invisible(fun()) 
...
In file included from /Library/Frameworks/R.framework/Resources/include/R.h:47:
In file included from /usr/local/Cellar/llvm/7.0.0/include/c++/v1/cstdlib:86:
/usr/local/Cellar/llvm/7.0.0/include/c++/v1/stdlib.h:94:15: fatal error: 'stdlib.h' file not found
#include_next <stdlib.h>
              ^~~~~~~~~~
1 error generated.

Installing the header files 'macOS_SDK_headers_for_macOS_10.14' fixes the problem on macOS Mojave 10.14.6; see Cannot find stdio.h.

The reason: The Command Line Tools package installs the macOS system headers inside the macOS SDK. Software that compiles with the installed tools will search for macOS headers at the standard include path: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include. For legacy software that looks for the macOS headers in the base system under /usr/include, please install the package file located at: /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14. pkg

gfortran

macOS does not include gfortran. So we cannot compile package like quantreg which is required by the car package. Another example is robustbase package.

Development Tools and Libraries for R of R on Mac OS X.

For now, I am using gfortran 6.1 downloaded from https://gcc.gnu.org/wiki/GFortranBinaries#MacOS on my OS X El Capitan (10.11).

data.table and enable OpenMP

See data.table

Fatal error 'stdlib.h' file not found

/Library/Frameworks/R.framework/Resources/include/R.h::55:11: fatal error: 'stdlib.h' file not found

The error happens when R is trying to update the partykit package

See Header file location.

stdlib.h not found when installing R package on mac #137.

MacTex

Install BasicTex.pkg.

Then we can install new packages by

sudo /Library/TeX/texbin/tlmgr update --self
sudo /Library/TeX/texbin/tlmgr install titling \
     --repository=http://ftp.dante.de/tex-archive/systems/texlive/tlnet

Note tlmgr (TeX Live package manager) program is not only for macOS. To use the GUI tlmgr, the system needs to install perl-tk. However there is no instruction to do that on macOS.

# List installed packages
tlmgr list --only-installed

# List all available packages
tlmgr list

R also has a package to use tlmgr from within R. See tlmgr() function from tinytex package.

Install R on Chrome OS

Linux beta

Installing R and RStudio on a Chromebook. Note: although my chromebook also supports Linux beta, my chromebook is not intel based. So the instruction for installing RStudio will not work in my case. But the installation of R part still works. I just need to use R from a terminal. Also the X11 window for plotting works perfectly. Update (2019/6/6): I could not install "ggplot2". In fact, R itself is screwed up after an attempt to install "ggplot2". At the same time, 'gedit' (see below) is not working anymore.

By the way I am able to install gedit in Linux app.

Crouton

Tested on Lenovo Chromebook s330 (MediaTek™ MTK8173C Processor (1.70GHz) 4-core, 4GB memory, 32GB storage)

  1. Install crouton. See here.
  2. Install binary version of R does not work (Xenial + xfce). The following packages have unmet dependencies: r-base : Depends: r-base-core (>=3.5.2-1xenial) but it is not going to be installed... E: Unable to correct problems, you have held broken packages.
  3. Install from source
sudo apt-get build-dep r-base
wget https://cran.rstudio.com/src/base/R-3/R-3.5.2.tar.gz
tar xzvf R-3.5.2.tar.gz
cd R-3.5.2
./configure --enable-R-shlib
make -j4
sudo make install

Best OS for R users

This post by Jim Hester

Testing R on Emulated Platforms

Testing R on Emulated Platforms

Upgrade R

Installing multiple R and Bioconductor versions

Installing multiple R and Bioconductor versions 2021-04-30

System libraries

> R.version.string
[1] "R version 3.6.2 (2019-12-12)"
> rownames( installed.packages("/usr/local/lib/R/library") )
 [1] "base"       "boot"       "class"      "cluster"    "codetools" 
 [6] "compiler"   "datasets"   "foreign"    "graphics"   "grDevices" 
[11] "grid"       "KernSmooth" "lattice"    "MASS"       "Matrix"    
[16] "methods"    "mgcv"       "nlme"       "nnet"       "parallel"  
[21] "rpart"      "spatial"    "splines"    "stats"      "stats4"    
[26] "survival"   "tcltk"      "tools"      "utils"     

Link Time Optimization (LTO)