R Programming - Part 1 - Basic Operations

01 Oct 2020 - Benjamin Loi

Introduction

This article will describe the commonly used object types in R, and their respective operations.

Variables, Objects and Assignment

In R, we deal with different objects, like numbers, vectors and matrices. Making reference to such objects required assigning them to a variable that can be manipulated later. To do so, we will use the assignment operator <- where the left hand side is the variable name and the right hand side is the object. The figure below demonstrates the assignment and printing of a number.

R-01-00
R-01-01

Basic Mathematical Operations

Basic mathematical operations, like addition, subtraction, multiplication, and division, can be done by +, -, *, /, between numbers or variables. Exponentiation can be done by **, or in the format of scientific notation e+ and e-, which means ten to the power of n. The order of evaluation follows the common mathmatical usage, and brackets, having the highest priority, can be added to the expression. The results of mathematical operations can also be assigned to a variable. The example below shows the results of mathmetical operations on some numbers.

R-01-02
R-01-03

Vectors and Related Operations

We also have objects representing vectors and matrices in R. To create a vector, use c() with the entries as input, where c stands for column. A convenient way to create a sequence of numbers within a range is to use :, with a step of 1. This is useful in constructing a vector. Mathematical operators acting between two vectors are element-wise, applied each pair by each pair. Meanwhile mathmatical operations between a vector and a single number will have the effect of applying the operator on all entries in that vector against the scalar. They are collectively called as whole array operations. Those behaviors are demonstrated below.

R-01-04

Vector Slicing

We can select parts of a vector by slicing notation, by specifying the desired index in a bracket [] following the vector name. The index can be supplied in the form of a sequence of number, either generated from : as mentioned in the last paragraph, or another vector. An example usage is shown below. The extracted subset can be used in further calculation as long as the extents of the dimensions agree. Notice that the indexing always starts from 1, different from 0 for many other programming languages.

R-01-05

Previous: Part 0 - Installation Next: Part 2 - Functions

Last Update: 2020-10-12