0% found this document useful (0 votes)
6 views21 pages

Introduction to R Programming Basics

The document introduces R and Python as essential programming languages for statistical computing and data analysis, detailing their origins, environments, installation processes, and available packages. R, developed as an open-source alternative to the S language, offers a wide range of statistical functions and is supported by a community of developers, while Python is a versatile, high-level language favored for its simplicity and extensive libraries for scientific computing. The document also covers integrated development environments (IDEs) for both languages, installation instructions, and useful commands for users.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views21 pages

Introduction to R Programming Basics

The document introduces R and Python as essential programming languages for statistical computing and data analysis, detailing their origins, environments, installation processes, and available packages. R, developed as an open-source alternative to the S language, offers a wide range of statistical functions and is supported by a community of developers, while Python is a versatile, high-level language favored for its simplicity and extensive libraries for scientific computing. The document also covers integrated development environments (IDEs) for both languages, installation instructions, and useful commands for users.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CHAPTER 1

Introduction to R and Python

1.1 Introduction to R
R is a language and package-based software environment that provides a
wide variety of functions for statistical computing and graphics. R is a project
of GNU, and its root depends on S language with some differences.
S language and environment was developed by John Chambers and his col-
leagues at Bell Laboratories (formerly AT&T and now Lucent Technolo-
gies). While S language provides programmable research tools for
statistical analysis, R has evolved as an Open Source alternative of the
S language. R was initially developed by Robert Gentleman and Ross Ihaka
at the statistics department of the University of Auckland. Its name “R”
comes from the first letters of its developers. Besides its statistical capabilities
(such as linear and nonlinear modelling, classical statistical tests, time-series
analysis, classification, clustering, etc.), high-resolution publication-quality
plots can be produced with full control of the users. R is distributed under
the terms of Free Software Foundation’s GNU GPL license. Thanks to
terms of this license, source codes of both base distribution and external
packages with GPL license can be accessed, modified, and re-distributed
by the user. Therefore, data analysts can view and contribute to source codes
of these packages by accessing the running algorithms and adding their spe-
cific functions. As a result, scientists and students at universities can
use R freely and without a license fee. The use of free software in
science encourages and improves worldwide collaboration on data-analysis
approaches. Also, R is used in teaching statistics at undergraduate and grad-
uate levels at universities since students can freely use these statistical
tools [1, 2].
The base distribution of R is maintained by the R Development Core
Team since 1997. In addition, a huge group of volunteer developers con-
tribute to the project by developing new packages or upgrading existing
add-on packages to improve their functionalities. The project’s website is
the main official information source and can be reached from Fig. 1.1:
[Link]

R and Python for Oceanographers © 2019 Elsevier Inc.


[Link] All rights reserved. 1
2 R and Python for Oceanographers

Fig. 1.1 A view of official R-Project website.

1.2 R environment
R statistical environment system is composed of two main parts: base-
distribution system and add-on packages.

1.2.1 Base system of R


The base system consists of core functions required to run R language. Also,
core statistical functions (stats package) and graphical tools (graphics pack-
age) are included as dependencies of other add-on packages. Core packages
included in the installation media of base system cover standard statistical
functions, such as statistical tests, linear models, non-linear models, data-
handling functions, clustering functions, and survival-test functions. A list
of packages within the base system (included in R version 3.4.0) is
given below.
A list of base distribution packages:

base methods tools


compiler parallel translations
datasets splines utils
graphics stats
grDevices stats4
grid tcltk
Introduction to R and Python 3

1.2.2 Add-on packages


Add-on packages are developed and maintained by the user community.
These packages contain many advanced statistical, computational, and
graphical functions. Some of the packages have dependencies on other
packages.
Examples of add-on packages:

agricolae maps
car plyr
ggplot2 psych
lattice

1.3 Installation of R
1.3.1 Installation of R base software
R is an open source software, and it can be downloaded and installed freely.
Latest/older versions of R software for Windows, Linux, or Mac OSX oper-
ating systems could be downloaded and installed from [Link]
org/ (Fig. 1.2).
In Linux systems, like Ubuntu, the latest version of R base (r-base) envi-
ronment can be installed from Software Center by adding official reposito-
ries of R-CRAN (Comprehensive R Archive Network) to the repository
list. In Debian systems, latest R version can be installed from Package Man-
ager after adding appropriate CRAN repositories. In Mac OSX systems, the
latest version of R can be downloaded from its official website and installed
according to the instructions.

1.3.2 Installation of add-on packages


You can install add-on packages from the internet into the package library
folder under R installation directory or any user-defined library folder as
below:
# install into default package library folder

[Link]("package_name")

# install into user defined library folder

[Link]("package_name", lib='C:\Program Files\R\R-


version\library')
4
R and Python for Oceanographers
Fig. 1.2 A view of R-Project download page.
Introduction to R and Python 5

Or you can install packages from the R console application under the Pack-
ages menu by clicking the install packages option. Then, you can select the
desired package to install from the drop-down list of add-on packages.
Alternatively, you can install a previously downloaded package from a
local file by following these instructions:
1. First download the latest versions of packages with their dependencies
from CRAN
2. Create PACKAGE and [Link] logs for packages in the directory
with these codes:

library(tools)

write_PACKAGES("C:/Users/username/r_packages")

3. Delete [Link] file


4. Run this code to install the package:

[Link]("package_name", contriburl="file:
C:/Users/username/r_packages ")

Optionally, the latest or test versions of some packages can be installed


directly from its Github page maintained by its user:
1. First install devtools package that allows the installation of packages from
Github repository as well as it provides many useful tools:

[Link]("devtools",
lib="file:C:/Users/username/r_packages")

2. Install desired package from its Github repository:

devtools::install_github("Github_username/package_name")

You can test the installation of add-on packages by loading them from
R console with this code:

library(package_name)

If the code runs without any errors, this means the installation of the package
was successful.
6 R and Python for Oceanographers

1.4 Integrated development environments (IDEs)


and editors for R
Commands, functions, and scripts of R language can be edited and saved
with lightweight and user-friendly code editors like Notepad++, RKWard,
Rgedit, Atom, Vim with Nvim-R plugin, Emacs with ESS plugin as well as
with other text editors. Some of these editors provide code highlighting,
autocompletion, and syntax error-checking functions. Behind these editors,
IDEs like Official R Console and Editor, R Studio, and Tinn-R have addi-
tional code execution and plotting capabilities. These IDEs have multi-panel
systems within a single application window, allowing the user to manage
scripts easier and faster.

1.4.1 Official R console and editor


R base software installation comes with an R editor for writing of com-
mands/scripts and an R console for execution of commands (Fig. 1.3).
The console is an interpreter of R language and works like a command line
interface such as CMD in Windows and Terminal in Linux systems. It is
possible to run saved scripts from a file and to load and save workspace
and history of commands. It is also possible to manage packages and to open
help files from the main menu bar.

1.4.2 RStudio
RStudio is a free and open source IDE for R language (Fig. 1.4). Compared
to official R console, it provides many advantages for editing and running of
scripts. RStudio is available for Windows, Linux, and Mac OSX systems.
More information about RStudio can be found at its official website:
[Link]

1.5 Useful R commands


# show version number of R and installed OS

sessionInfo()

# show R version

getRversion()
Introduction to R and Python
Fig. 1.3 A screenshot of R editor and console.

7
8
R and Python for Oceanographers
Fig. 1.4 A screenshot of RStudio.
Introduction to R and Python 9

# show current working directory

getwd()

# change working directory to a user defined location

setwd("C:/...")

# list all packages in the R package library

library()

# open download mirrors list for package installation

[Link]()

# download R packages from CRAN repository to a local folder

[Link]("package_name", "download_directory")

# update all packages

[Link](checkBuilt=TRUE)

# show version numbers of R packages, dependencies of packages, recom-


mended packages, license info and builded R version number

[Link]()

# parses and returns the description file of a package

packageDescription("package_name")

# remove packages

[Link]("package_name", "installed_directory")

# show license info

license()
10 R and Python for Oceanographers

# display citation

citation()

# attach packages

library(package_name)

# detach packages

detach("package:package_name")

# list all packages in the default library

library([Link] = .Library)

# list loaded packages

search()

# running time of R

[Link]()

# current memory usage

[Link]()

# total available memory

[Link]()

# terminate an R session

q()

# display warning messages

warnings()
Introduction to R and Python 11

# display the commands history

history()

# load the commands history

loadhistory(file = ".Rhistory")

# save the commands history

savehistory(file = ".Rhistory")

# Save R image

[Link]("C:\\Users\\username\\...\\[Link]")

[Link]("C:\\Users\\user\\...\\[Link]")

1.6 Getting help for R


Both online and offline help documentations and manuals for R are avail-
able. You can start help while using R with [Link]() function from the
console. For more help, you can use online documentations from the official
R website by using these links:
• Help page: [Link]
• Manuals page: [Link]
• Frequently Asked Questions (FAQs) Page: [Link]
[Link]

1.7 Introduction to Python


Python is an interpreted, general-purpose, object-oriented and high-level
programming language. It was conceived by Guido van Rossum in the late
1980s, and its first implementation started in 1989. Python is developed as a
successor of ABC language at Centrum Wiskunde & Informatica (CWI) in
the Netherlands. In the development of Python, van Rossum also influ-
enced from Modula-3. As a result, Python has been evolved as a new
language that includes improvements over ABC and Modula-3 [3, 4].
12 R and Python for Oceanographers

Currently, the development of Python language is organized and supported


by Python Software Foundation (PSF).
Some advantages of Python as a data science tool are:
– It is simple, readable, and easy to learn.
– Python interpreter can run on multiple platforms: Windows, Linux, and
Mac OSX.
– It is possible to express functions with fewer codes compared to other
languages.
– It is an open source language and can be freely used and distributed.
– There are many libraries for scientific computing.
– It is possible to use Python in combination with other languages such as
C or C++.

1.8 Modules and packages in Python


The power of Python language depends on the availability of modules and
packages for wide ranges of applications. A module is a file that contains
functions and definitions [5]. Modules include pre-defined and special func-
tions, and they are imported at the start of Python scripts when needed.
Modules are created to keep functions modular and separate.
A package is a collection of related modules in a single hierarchical struc-
ture [6]. Packages can be very complex to include hundreds of individual
modules. Some examples of widely used and fundamental scientific Python
packages are: NumPy, SciPy, Matplotlib, Pandas, Sympy, IPython, scikit-
learn, seaborn, and SciTools.
These packages provide the following functionalities:
– NumPy is a base package for N-dimensional arrays, linear algebra, inte-
gration of C/C++, and Fortran codes, etc.
– SciPy is a fundamental library for scientific computing, such as numerical
integration and optimization.
– Matplotlib is a 2D plotting library for high quality and publication-ready
figures.
– Pandas provides high-performance data structure and data analysis tools.
– Sympy is a symbolic mathematics library.
– IPython is an enhanced interactive console for Python.
– scikit-learn is a machine learning library.
– seaborn is a matplotlib based visualization library for statistical graphics.
– SciTools is a scientific computing library built on top of other widely used
packages such as NumPy, SciPy, Gnuplot, etc.
Introduction to R and Python 13

1.9 Python IDEs


There are many IDEs for editing and running python scripts. This multi-
purpose software provides ease of writing, highlighting and formatting codes
as well as finding syntax errors. They also provide autocompletion function
and file/path browser for easy handling of script files. Some examples of
IDEs for scientific computing are: Python IDLE (Python’s Official Inte-
grated Development and Learning Environment), Eclipse, Eric and Spyder.
Application previews of Python IDLE and Spyder are given at Figs. 1.5 and
1.6, respectively.

1.10 Installing Python and scientific Python distributions


Python comes pre-installed in Linux and Mac OSX systems. In Windows,
Python interpreter could be installed from [Link]
downloads/windows/. In Linux and Mac OSX systems, individual scientific
python packages could be added to local python libraries.
In Linux and Mac OSX systems, standalone python packages (installation
of SciPy stack given as an example) could be installed by using one of the
below options:

1.10.1 Using pip package


To use this option, Python and pip should be already installed on your
system.
First, upgrade the pip package:

python -m pip install –upgrade pip

Then, install the latest version of a module and its dependencies from the
Python Packaging Index (PyPI):

python -m pip install package_name

For example, install SciPy stack using user option:

pip install –user numpy scipy matplotlib ipython jupyter


pandas sympy nose

Add user installation directory to system’s PATH by,


14
R and Python for Oceanographers
Fig. 1.5 A screenshot of Python IDLE.
Introduction to R and Python
Fig. 1.6 A screenshot of Spyder IDE.

15
16 R and Python for Oceanographers

For Linux:
# Add below command to the end of your /.bashrc file

export PATH="$PATH:/home/your_user/.local/bin"

For Mac OSX,


# Add below command to the end of your /.bash_profile file

export PATH="$PATH:/Users/your_user/Library/Python/3.5/bin"

Change “your_user” with your username and “3.5” with Python version
installed on your system.

1.10.2 Using package managers


Depending on the availability of packages and their update status on the
repositories of your operating system, this option might install latest/previ-
ous versions of packages.
In Linux, you can choose from these options, depending on your
distribution:
For Ubuntu or Debian systems,

sudo apt-get install package_name

For example, to install SciPy stack using this option:

sudo apt-get install python-numpy python-scipy python-


matplotlib ipython ipython-notebook python-pandas python-
sympy python-nose

For Fedora:

sudo dnf install package_name

For example, to install SciPy stack using this option,

sudo dnf install numpy scipy python-matplotlib ipython


python-pandas sympy python-nose atlas-devel
Introduction to R and Python 17

1.10.3 Using source files of packages


If package files are not found at PyPI and at repositories of your operating
system, you can use this option. First, download the latest source code of the
package to a local directory. Uncompress the installation files from the
downloaded source file (usually compressed as [Link] or zip files). Then,
run these codes to install the package:
For Linux systems

python [Link] install

For Windows

[Link] install

Detailed instructions for installation of SciPy stack could be found at https://


[Link]/[Link]. Depending on their availabilities at your sys-
tem’s repositories, other python packages could also be installed by using
package managers or by installing from their source files.
For windows systems, scientific python distributions are the easiest solu-
tion to use scientific python packages. They provide a great number of pack-
ages with a single software installation. Canopy (by Enthought), Anaconda
(by Continuum Analytics), and Python(x,y) are among several scientific
python distributions that are free to use for educational and academic pur-
poses. Canopy and Anaconda are multi-platform (Windows, Linux, and
Mac OS-X versions are available) distributions with the support of the latest
package updates, whereas Python(X,Y) is only available for Windows sys-
tems with update schedules at longer intervals. An application preview of
Canopy Editor is given at Fig. 1.7 as an example.
Some advantages of using these scientific python distributions are as
follows:
– Python packages are automatically installed along with Python
environment.
– It is possible to manage packages from GUI package managers.
– Python code editor and interpreter are provided in the same application
window.
Download links for the latest and older versions of Canopy, Anaconda,
Miniconda and Python(x,y). Distributions are given below:
– Canopy: [Link]
– Anaconda: [Link]
18
R and Python for Oceanographers
Fig. 1.7 A screenshot of Canopy Editor.
Introduction to R and Python 19

– Miniconda: [Link]
– Python(x,y): [Link]
To test the Python installation:
– Open terminal (in Linux/Mac OSX)/command prompt (in Windows),
type python and press enter or click Python icon from the start menu.
– Then, run the following code at the Python shell:

import sys
print sys.version_info

– If you get the below output, it means that Python (version 2) works with-
out any problem on your system.

sys.version_info(major=2, minor=..., micro=..., ...)

1.11 Getting help for Python


Python has online and offline help documentations. You can start help while
using Python with help() function from the console. For more help, you can
use online documentations from the official Python website by using the
following links.
• Documentation page: [Link]
• Help page: [Link]
• FAQs page: [Link] or [Link]
org/3/faq/

1.12 Some useful packages and libraries in R


and Python for oceanography
In R and Python, some packages useful for oceanographic and geographical
purposes are as follows:

R packages Python libraries


• OceanView • numpy
• marelac • matplotlib
• oce • pandas
• ocedata • basemap
• oceanmap • scipy
• maps • netcdf4
Continued
20 R and Python for Oceanographers

R packages Python libraries


• mapdata • iris
• mapproj • cartopy
• rworldmap • gsw
• rworldxtra • seawater
• ggmap • oceans
• rgdal • rgdal
• geosphere • geos
• OpenStreetMap • shapely
• rgeos • ctd
• maptools • proj4
• marmap • pyproj
• GISTools • pyshp
• PBSmapping • geopandas
• spatialkernel • geoplot
• geoR • GeoRasters
• automap • gridded
• RNetCDF • seabird

In this book, R examples were prepared with R version > 3 and tested
with latest R 3.5.1 version.
Python examples were prepared and tested with package versions in
Miniconda Python Environment.
A simple conda environment can be created, and necessary packages can
be installed from command line/terminal by typing:
# Create python environment

conda create -n env_name python=2

# Activate new environment

conda activate env_name

# Install packages

conda install -n env_name numpy=1.11.3 matplotlib=1.5.3


pandas=0.17.0 basemap=1.0.7 scipy=0.19.1 netcdf4=1.2.4
cartopy=0.14.3 gsw=3.0.6 seawater=3.3.4 oceans=0.4.0
netcdftime iris=1.9.2 geopy=1.11.0 cmocean

# Install seabird package with pip

pip install seabird


Introduction to R and Python 21

References
[1] B.S. Everitt, T. Hothorn, A Handbook of Statistical Analyses Using R, second ed., CRC
Press, Florida, 2010.
[2] R-Project Website, About R, n.d. [Link] Accessed
01 September 2017.
[3] A. Boschetti, L. Massaron, Python Data Science Essentials, first ed., Pack Publishing,
Birmingham, 2015.
[4] Python Documentation, Foreword for “Programming Python” n.d. (1st ed.), http://
[Link]/doc/essays/foreword/. Accessed 01 September 2017.
[5] Python Documentation, n.d. Modules, [Link]
html. Accessed 01 September 2017.
[6] Python Documentation, n.d. Packages, [Link]
html#packages. Accessed 01 September 2017.

Common questions

Powered by AI

Reusability in R and Python's package ecosystems allows researchers to apply, modify, and share pre-existing code and algorithms, facilitating collaborative research by building on existing knowledge and resources. This practice not only conserves effort but also promotes validation and enhancement of scientific work across various domains .

R's open-source nature under GNU GPL license allows free and unrestricted use by academics and scientists. This fosters a collaborative environment where researchers can contribute to and improve statistical methodologies, promoting innovation and sharing of knowledge without the barrier of licensing fees .

Community-contributed packages have been pivotal in the evolution of R, providing a vast array of specialized functions that extend beyond standard capabilities. This collective input diversifies R's applications, supports innovation, and accelerates the integration of cutting-edge statistical methods into readily available packages .

IDEs like RStudio provide enhanced capabilities for managing scripts such as code execution and visualization through multi-panel systems, compared to traditional text editors. They deliver features like code highlighting, autocompletion, and error-checking, which streamline coding tasks, offering a more integrated and efficient programming environment .

Add-on packages, developed and maintained by the user community, provide advanced statistical, computational, and graphical functions that extend the core functionalities of the R base system. Since some packages have dependencies on others, they form a comprehensive ecosystem that enhances the flexibility and capability of R for diverse data analysis tasks .

The integration of R and Python in oceanography is driven by their respective strengths in statistical analysis and computational efficiency. R's robust statistical packages and Python's powerful data manipulation libraries allow for comprehensive analysis and visualization of oceanographic data, offering holistic insights and aiding in sophisticated modeling and prediction tasks .

R software can be installed on Windows, Linux, or Mac OSX by downloading from CRAN. In Linux, using package managers like apt-get or Software Center with CRAN repositories is common, while Mac users download directly from the official site. Package management is efficiently handled by using install.packages() to add packages and devtools for GitHub sources .

Scientific Python distributions such as Anaconda and Canopy simplify package installation by providing a large suite of packages within a single installation, along with GUI-based package management. This contrasts with traditional package installation, which involves manual installation via pip or system package managers, simplifying setup and maintenance .

R evolved as an open-source alternative to the S language, providing similar programmable research tools for statistical analysis while allowing for greater accessibility and community contribution due to its GNU GPL license. This open-source nature enables users to view, modify, and redistribute source codes, which encourages global collaboration on data-analysis approaches .

Python libraries such as NumPy and SciPy offer modular structures with specific functionalities like numerical operations and optimization. This modularity allows users to only employ necessary components, ensuring memory efficiency and enabling targeted computational tasks, thus enhancing Python's role in scientific computing .

You might also like